bool Font::GenerateGlyph( unsigned int glyphNumber, GlyphBitmap &glyphBitmap) { if(FT_Load_Glyph( face, FT_Get_Char_Index( face, glyphNumber ), FT_LOAD_DEFAULT )) { return false; } FT_Glyph glyph; if(FT_Get_Glyph( face->glyph, &glyph )) { return false; } FT_Glyph_To_Bitmap( &glyph, ft_render_mode_normal, 0, 1 ); FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph; FT_Bitmap &bitmap=bitmap_glyph->bitmap; glyphBitmap.bitmap->Generate(Bitmap::FORMAT_RGBA, bitmap.width, bitmap.rows, 0x00000000); unsigned int channelCount = GetChannelCount(Bitmap::FORMAT_RGBA); byte *glyphImageData = glyphBitmap.bitmap->GetData(); for(int j = 0; j < bitmap.rows; j++) { for(int i=0; i < bitmap.width; i++) { glyphImageData[( bitmap.width * j + i ) * channelCount + channelCount - 1] = bitmap.buffer[bitmap.width * ( bitmap.rows - j - 1) + i]; } } glyphBitmap.offsetDown = bitmap_glyph->top - bitmap.rows; glyphBitmap.bitmap->BlackToWhite(); return true; }
ImageHandle FreeTypeFont::createGlyphImage(int codepoint, int fontSize) const { int glyph_index = FT_Get_Char_Index( fontInfo->face, codepoint ); int error = FT_Set_Pixel_Sizes( fontInfo->face, /* handle to face object */ 0, /* pixel_width */ fontSize ); /* pixel_height */ if ( error ) LogError("Error setting font size"); error = FT_Load_Glyph( fontInfo->face, glyph_index, FT_LOAD_RENDER | FT_LOAD_TARGET_LCD); if ( error ) LogError("Error loading glyph"); FT_Glyph glyph; /* a handle to the glyph image */ error = FT_Get_Glyph( fontInfo->face->glyph, &glyph ); if ( error ) LogError("Error getting glyph"); FT_Vector origin; origin.x = origin.y = 0; error = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_LCD, &origin, 1 ); FT_Bitmap bitmap = ((FT_BitmapGlyph) glyph)->bitmap; if (bitmap.width == 0 || bitmap.rows == 0) return HandleInvalid; auto image = ImageCreate(AllocatorGetHeap(), bitmap.width/3, bitmap.rows, PixelFormat::R8G8B8); image.Resolve()->setBuffer(bitmap.buffer, bitmap.pitch); return image; }
FT_BitmapGlyphRec* CFontEngine::RenderGlyph(char Char) { auto glyphIter = m_CachedGlyphMap.find(Char); if (glyphIter == m_CachedGlyphMap.end()) { if (FT_Load_Char(m_FontFace, Char, FT_LOAD_DEFAULT)) { throw(Wg_Ex_FreeType("Unable to render glyph.", "CFontEngine::RenderGlyph")); } FT_Glyph glyph; if (FT_Get_Glyph(m_FontFace->glyph, &glyph)) { throw(Wg_Ex_FreeType("Unable to copy glyph.", "CFontEngine::RenderGlyph")); } if (FT_Glyph_To_Bitmap(&glyph, ft_render_mode_normal, nullptr, 1)) { throw(Wg_Ex_FreeType("Unable to render glyph.", "CFontEngine::RenderGlyph")); } glyphIter = m_CachedGlyphMap.insert(std::make_pair(Char, *reinterpret_cast<FT_BitmapGlyph>(glyph))).first; } return &(glyphIter->second); }
void grid_text_renderer<T>::render(glyph_positions const& pos, value_integer feature_id) { glyphs_.clear(); prepare_glyphs(pos); FT_Error error; FT_Vector start; unsigned height = pixmap_.height(); pixel_position const& base_point = pos.get_base_point(); start.x = static_cast<FT_Pos>(base_point.x * (1 << 6)); start.y = static_cast<FT_Pos>((height - base_point.y) * (1 << 6)); start.x += transform_.tx * 64; start.y += transform_.ty * 64; // now render transformed glyphs double halo_radius = 0.0; FT_Matrix halo_matrix; halo_matrix.xx = halo_transform_.sx * 0x10000L; halo_matrix.xy = halo_transform_.shx * 0x10000L; halo_matrix.yy = halo_transform_.sy * 0x10000L; halo_matrix.yx = halo_transform_.shy * 0x10000L; for (auto & glyph : glyphs_) { halo_radius = glyph.properties.halo_radius * scale_factor_; FT_Glyph_Transform(glyph.image, &halo_matrix, &start); error = FT_Glyph_To_Bitmap(&glyph.image, FT_RENDER_MODE_NORMAL, 0, 1); if (!error) { FT_BitmapGlyph bit = reinterpret_cast<FT_BitmapGlyph>(glyph.image); render_halo_id(&bit->bitmap, feature_id, bit->left, height - bit->top, static_cast<int>(halo_radius)); } FT_Done_Glyph(glyph.image); } }
void FontPrintImageTtf_short(ge_Font* font, int x, int y, const unsigned short* text, u32 color, ge_Image* image){ FT_GlyphSlot slot = ((FT_Face)font->face)->glyph; int b_x = x; int n = 0; long ch = 0; for (n = 0; text[n] != 0x0; n++) { // gePrintDebug(0x100, "char: %d\n", n); ch = (u16)text[n]; if(ch == '\n'){ y += font->size; x = b_x; continue; } if(ch >= 0x80){ TransformUnicodeChar(&ch); } FT_UInt glyph_index = FT_Get_Char_Index(((FT_Face)font->face), ch); FT_Load_Glyph(((FT_Face)font->face), glyph_index, FT_LOAD_DEFAULT); FT_Glyph glyph; FT_Get_Glyph(((FT_Face)font->face)->glyph, &glyph); FT_Glyph_To_Bitmap(&glyph, ft_render_mode_normal, 0, 1); slot = ((FT_Face)font->face)->glyph; FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph; FT_Bitmap bitmap = bitmap_glyph->bitmap; fontPrintTextImage(&bitmap, x+bitmap_glyph->left, y+font->size-bitmap_glyph->top, color, image); x += slot->advance.x >> 6; } geUpdateImage(image); }
static void freetype2_drawtext(PFont pfont, image_p pimage, int x, int y, const void *text, int cc, int flags) { PFontFreetype pf = (PFontFreetype) pfont; uint16_t* value; FT_Glyph glyph; int pen_x = x; int pen_y = y + pf->size; int i; FT_BitmapGlyph bitmap_glyph; FT_Bitmap* bitmap; value = _nge_ft_conv_encoding(pfont, text, &cc); if (cc <= 0) return; if(pimage->swizzle ==1){ unswizzle_swap(pimage); pimage->dontswizzle = 1; } pimage->modified =1; for (i =0;i<cc;i++) { FT_Load_Glyph( pf->face, FT_Get_Char_Index( pf->face, value[i] ), FT_LOAD_DEFAULT ); if(pf->flags & FLAGS_FREETYPE_BOLD) FT_GlyphSlot_Embolden(pf->face->glyph); if(pf->flags & FLAGS_FREETYPE_ITALICS) FT_GlyphSlot_Oblique(pf->face->glyph); FT_Get_Glyph( pf->face->glyph, &glyph ); FT_Render_Glyph( pf->face->glyph, ft_render_mode_normal ); FT_Glyph_To_Bitmap( &glyph, ft_render_mode_normal, 0, 1 ); bitmap_glyph = (FT_BitmapGlyph)glyph; bitmap=&bitmap_glyph->bitmap; draw_one_word(pf,bitmap,pimage,pen_x + pf->face->glyph->bitmap_left,pen_y - pf->face->glyph->bitmap_top ); pen_x +=(pf->face->glyph->advance.x+pf->fix_width*72) >> 6 ; FT_Done_Glyph( glyph ); } }
static void ft2_draw_glyphs(GalDrawable drawable, GalPB pb, GalFont obj, GalRect *area, eint x, eint y, GalGlyph *glyphs, eint len) { Ft2Font *ft2font = FT2_FONT_DATA(obj); GalImage *image = ft2font->image; FT_Face face = ft2_get_face(ft2font); FT_BitmapGlyph bitmap_glyph; FT_Bitmap *bitmap; eint i, w = 0; egal_fill_image(image, 0, area->x, 0, area->w, image->h); for (i = 0; i < len; i++) { FT_Glyph glyph; FT_Load_Glyph(face, glyphs[i].glyph, FT_LOAD_DEFAULT); FT_Get_Glyph(face->glyph, &glyph); if (face->glyph->format != ft_glyph_format_bitmap) FT_Render_Glyph(face->glyph, ft_render_mode_normal); FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1); bitmap_glyph = (FT_BitmapGlyph)glyph; bitmap = &bitmap_glyph->bitmap; ft2_bitmap_to_image(bitmap, image, x + w + face->glyph->bitmap_left, ft2font->metrics.height - face->glyph->bitmap_top + ft2font->metrics.descent); w += glyphs[i].w; } { GalRect rc = {x, y, w, ft2font->metrics.height}; egal_rect_intersect(&rc, &rc, area); eint _y = rc.y - y; egal_composite_image(drawable, pb, rc.x, rc.y, image, rc.x, _y, rc.w, rc.h - _y); //egal_draw_image(drawable, pb, rc.x, rc.y, image, rc.x, _y, rc.w, rc.h - _y); } }
bool Font::CreateFromFile( const char* path, const uint32_t font_size, const bool smooth, const uint32_t start_char, const size_t num_chars ) { if( path == NULL || font_size == 0 || num_chars == 0 || _num_glyphs > 0 ) return false; Mojo::Services::Filesystem* filesystem = MOJO_GET_SERVICE(Filesystem); Mojo::Filesystem::File* file = filesystem->Open(path, Mojo::Filesystem::FILE_READ); if( !file ) return false; size_t file_len = filesystem->Length(file); if( file_len == 0 ) { filesystem->Close(file); return false; } // todo: Use FT_Open_Face to read the file instead? uint8_t* buffer = new uint8_t[file_len]; { uint32_t num_bytes_read = 0; while( num_bytes_read < file_len ) { size_t read = filesystem->Read(file, file_len - num_bytes_read, (void*)&buffer[num_bytes_read]); mojo_assertf(read > 0, "Font::CreateFromFile\n -> Services/Filesystem error?\n"); num_bytes_read += read; } } filesystem->Close(file); FT_Face ft_face; if( FT_New_Memory_Face(Mojo::GetFreeTypeLibrary(), (const FT_Byte*)buffer, file_len, 0, &ft_face) ) { delete[] buffer; return false; } FT_Set_Char_Size(ft_face, font_size * 64, font_size * 64, 72, 72); const float line_height = ft_face->size->metrics.height >> 6; // Load the glyphs Font::Glyph* glyphs = new Font::Glyph[num_chars]; FT_Glyph* ft_glyphs = new FT_Glyph[num_chars]; FT_BitmapGlyph* bm_glyphs = (FT_BitmapGlyph*)ft_glyphs; float blo = 0.0f; uint32_t bm_max_width = 0, bm_max_height = 0; for( uint32_t i = 0; i < num_chars; ++i ) { FT_Load_Char(ft_face, start_char + i, FT_LOAD_DEFAULT); FT_Get_Glyph(ft_face->glyph, &ft_glyphs[i]); glyphs[i].x_advance = ft_face->glyph->advance.x >> 6; glyphs[i].y_advance = ft_face->glyph->advance.y >> 6; glyphs[i].x_bearing = (FT_HAS_VERTICAL(ft_face) ? ft_face->glyph->metrics.vertBearingX : ft_face->glyph->metrics.horiBearingX) >> 6; glyphs[i].y_bearing = (FT_HAS_VERTICAL(ft_face) ? ft_face->glyph->metrics.vertBearingY : ft_face->glyph->metrics.horiBearingY) >> 6; FT_Glyph_To_Bitmap(&ft_glyphs[i], smooth ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO, 0, 1); const FT_Bitmap bitmap = bm_glyphs[i]->bitmap; glyphs[i].width = bitmap.width; glyphs[i].height = bitmap.rows; bm_max_width = bm_max_width < bitmap.width ? bitmap.width : bm_max_width; bm_max_height = bm_max_height < bitmap.rows ? bitmap.rows : bm_max_height; const float gbl = -glyphs[i].y_bearing + glyphs[i].height; blo = (blo < gbl) ? gbl : blo; } // Determine the texture atlas size uint32_t atlas_width = 0, atlas_height = 0; { static const struct { uint32_t width, height, area; } atlas_sizes[] = { { 64, 64, 64 * 64 }, { 128, 128, 128 * 128 }, { 256, 256, 256 * 256 }, { 512, 512, 512 * 512 } }; uint32_t min_area = 0; for( uint32_t i = 0; i < num_chars; ++i ) min_area += uint32_t((glyphs[i].width + 2) * (bm_max_height + 2)); for( uint32_t i = 0; i < 4; ++i ) { if( atlas_sizes[i].area < min_area ) continue; const uint32_t index = (i > 3) ? 3 : i; atlas_width = atlas_sizes[index].width; atlas_height = atlas_sizes[index].height; break; } if( atlas_width == 0 || atlas_height == 0 ) { for( uint32_t i = 0; i < num_chars; ++i ) FT_Done_Glyph(ft_glyphs[i]); delete[] ft_glyphs; delete[] glyphs; FT_Done_Face(ft_face); delete[] buffer; return false; } } Mojo::TextureAtlas tex_atlas = Mojo::TextureAtlas(atlas_width, atlas_height, 32); Mojo::BookshelfTexturePacker tex_packer = Mojo::BookshelfTexturePacker(&tex_atlas); uint8_t* bm_buffer = new uint8_t[bm_max_width * bm_max_height * 4]; for( uint32_t i = 0; i < num_chars; ++i ) { const FT_Bitmap bitmap = bm_glyphs[i]->bitmap; if( bitmap.width == 0 || bitmap.rows == 0 ) continue; memset((void*)bm_buffer, 255, bm_max_width * bm_max_height * 4); switch( bitmap.pixel_mode ) { default: { mojo_assertf(0, "Font::CreateFromFile()\n -> Pixel mode not supported.\n"); } break; case FT_PIXEL_MODE_MONO: { const uint8_t* bm_pixels = (const uint8_t*)bitmap.buffer; const uint32_t y_offset = 0; for( uint32_t y = 0; y < bitmap.rows; ++y ) { for( uint32_t x = 0; x < bitmap.width; ++x ) bm_buffer[(x + y * bitmap.width) * 4 + 3] = ((bm_pixels[x / 8]) & (1 << (7 - (x % 8)))) ? 0xFF : 0x00; bm_pixels += bitmap.pitch; } } break; case FT_PIXEL_MODE_GRAY: { const uint8_t* bm_pixels = (const uint8_t*)bitmap.buffer; for( uint32_t y = 0; y < bitmap.rows; ++y ) { for( uint32_t x = 0; x < bitmap.width; ++x ) bm_buffer[(x + y * bitmap.width) * 4 + 3] = bm_pixels[x]; bm_pixels += bitmap.pitch; } } break; } Mojo::Recti packed_rect; if( !tex_packer.Pack(bitmap.width, bitmap.rows, 1, bm_buffer, packed_rect) ) { Mojo::DebugPrintf(DBG_WARNING, "Font::CreateFromFile()\n -> unable to pack character '%c'\n", i + start_char); } glyphs[i].tex_coords[0] = (float)packed_rect.x / atlas_width; glyphs[i].tex_coords[1] = (float)packed_rect.y / atlas_height; glyphs[i].tex_coords[2] = (float)(packed_rect.x + packed_rect.width) / atlas_width; glyphs[i].tex_coords[3] = (float)(packed_rect.y + packed_rect.height) / atlas_height; } delete[] bm_buffer; // Unload the glyphs for( uint32_t i = 0; i < num_chars; ++i ) FT_Done_Glyph(ft_glyphs[i]); delete[] ft_glyphs; FT_Done_Face(ft_face); delete[] buffer; // Update _font_atlas = tex_atlas.Compile(); _start_glyph = start_char; _num_glyphs = num_chars; _glyphs = glyphs; _base_line = bm_max_height - blo; _line_height = line_height; return true; }
int eTextPara::appendGlyph(Font *current_font, FT_Face current_face, FT_UInt glyphIndex, int flags, int rflags, int border, bool last, bool activate_newcolor, unsigned long newcolor) { int xadvance, top, left, width, height; pGlyph ng; if (border) { /* TODO: scale border radius with current_font scaling */ if (current_font->getGlyphImage(glyphIndex, &ng.image, &ng.borderimage, 64 * border)) return 1; if (ng.image && ng.image->format != FT_GLYPH_FORMAT_BITMAP) { FT_Glyph_To_Bitmap(&ng.image, FT_RENDER_MODE_NORMAL, NULL, 1); if (ng.image->format != FT_GLYPH_FORMAT_BITMAP) return 1; } if (ng.borderimage && ng.borderimage->format != FT_GLYPH_FORMAT_BITMAP) { FT_Glyph_To_Bitmap(&ng.borderimage, FT_RENDER_MODE_NORMAL, NULL, 1); if (ng.borderimage->format != FT_GLYPH_FORMAT_BITMAP) return 1; } FT_BitmapGlyph glyph = NULL; if (ng.borderimage) { xadvance = ng.borderimage->advance.x; /* * NOTE: our boundingbox calculation uses xadvance, and ignores glyph width. * This is fine for all glyphs, except the last one (i.e. rightmost, for left-to-right rendering) * For border glyphs, xadvance is significantly smaller than the glyph width. * In fact, border glyphs often have the same xadvance as normal glyphs, borders * are allowed to overlap. * As a result, the boundingbox is calculated too small, the actual glyphs won't * fit into it, and depending on the alignment, one of the borders on the sides * will be cut off. * Ideally, the boundingbox calculation should be rewritten, to use both advance and glyph dimensions. * However, for now we adjust xadvance of the last glyph, so the current calculation will produce * a better fitting boundingbox for border glyphs. * * The compensation equals half of the difference between 'normal' glyph width, * and border glyph width. (half the width difference is on the left, and half on the right * of the glyph, we only need to compensate for the part on the right) * And since xadvance is in 16.16 units, we use (dW/2) << 16 = dW << 15 */ if (last) xadvance += (((FT_BitmapGlyph)ng.borderimage)->bitmap.width - ((FT_BitmapGlyph)ng.image)->bitmap.width) << 15; glyph = (FT_BitmapGlyph)ng.borderimage; } else if (ng.image) { xadvance = ng.image->advance.x; glyph = (FT_BitmapGlyph)ng.image; } else { return 1; } xadvance >>= 16; top = glyph->top; left = glyph->left; width = glyph->bitmap.width; height = glyph->bitmap.rows; } else {
///Create a display list coresponding to the give character. void make_dlist ( FT_Face face, char ch, GLuint list_base, GLuint * tex_base ) { //The first thing we do is get FreeType to render our character //into a bitmap. This actually requires a couple of FreeType commands: //Load the Glyph for our character. if(FT_Load_Glyph( face, FT_Get_Char_Index( face, ch ), FT_LOAD_DEFAULT )) throw std::runtime_error("FT_Load_Glyph failed"); //Move the face's glyph into a Glyph object. FT_Glyph glyph; if(FT_Get_Glyph( face->glyph, &glyph )) throw std::runtime_error("FT_Get_Glyph failed"); //Convert the glyph to a bitmap. FT_Glyph_To_Bitmap( &glyph, ft_render_mode_normal, 0, 1 ); FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph; //This reference will make accessing the bitmap easier FT_Bitmap& bitmap=bitmap_glyph->bitmap; //Use our helper function to get the widths of //the bitmap data that we will need in order to create //our texture. int width = next_p2( bitmap.width ); int height = next_p2( bitmap.rows ); //Allocate memory for the texture data. GLubyte* expanded_data = new GLubyte[ 2 * width * height]; //Here we fill in the data for the expanded bitmap. //Notice that we are using two channel bitmap (one for //luminocity and one for alpha), but we assign //both luminocity and alpha to the value that we //find in the FreeType bitmap. //We use the ?: operator so that value which we use //will be 0 if we are in the padding zone, and whatever //is the the Freetype bitmap otherwise. for(int j=0; j <height; j++) { for(int i=0; i < width; i++) { expanded_data[2*(i+j*width)]= expanded_data[2*(i+j*width)+1] = (i>=bitmap.width || j>=bitmap.rows) ? 0 : bitmap.buffer[i + bitmap.width*j]; } } //Now we just setup some texture paramaters. glBindTexture( GL_TEXTURE_2D, tex_base[ch]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); //Here we actually create the texture itself, notice //that we are using GL_LUMINANCE_ALPHA to indicate that //we are using 2 channel data. glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expanded_data ); //With the texture created, we don't need to expanded data anymore delete [] expanded_data; //So now we can create the display list glNewList(list_base+ch,GL_COMPILE); glBindTexture(GL_TEXTURE_2D,tex_base[ch]); //first we need to move over a little so that //the character has the right amount of space //between it and the one before it. glTranslatef(bitmap_glyph->left,0,0); //Now we move down a little in the case that the //bitmap extends past the bottom of the line //(this is only true for characters like 'g' or 'y'. glPushMatrix(); glTranslatef(0,bitmap_glyph->top-bitmap.rows,0); //Now we need to account for the fact that many of //our textures are filled with empty padding space. //We figure what portion of the texture is used by //the actual character and store that information in //the x and y variables, then when we draw the //quad, we will only reference the parts of the texture //that we contain the character itself. float x=(float)bitmap.width / (float)width, y=(float)bitmap.rows / (float)height; //Here we draw the texturemaped quads. //The bitmap that we got from FreeType was not //oriented quite like we would like it to be, //so we need to link the texture to the quad //so that the result will be properly aligned. glBegin(GL_QUADS); glTexCoord2d(0,0); glVertex2f(0,bitmap.rows); glTexCoord2d(0,y); glVertex2f(0,0); glTexCoord2d(x,y); glVertex2f(bitmap.width,0); glTexCoord2d(x,0); glVertex2f(bitmap.width,bitmap.rows); glEnd(); glPopMatrix(); glTranslatef(face->glyph->advance.x >> 6 ,0,0); //increment the raster position as if we were a bitmap font. //(only needed if you want to calculate text length) //glBitmap(0,0,0,0,face->glyph->advance.x >> 6,0,NULL); //Finnish the display list glEndList(); }
bool TrueTypeFont::bakeGlyphDistance(CodePoint _codePoint, GlyphInfo& _glyphInfo, uint8_t* _outBuffer) { BX_CHECK(m_font != NULL, "TrueTypeFont not initialized"); _glyphInfo.glyphIndex = FT_Get_Char_Index(m_font->face, _codePoint); FT_Int32 loadMode = FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING; FT_Render_Mode renderMode = FT_RENDER_MODE_NORMAL; FT_GlyphSlot slot = m_font->face->glyph; FT_Error error = FT_Load_Glyph(m_font->face, _glyphInfo.glyphIndex, loadMode); if (error) { return false; } FT_Glyph glyph; error = FT_Get_Glyph(slot, &glyph); if (error) { return false; } error = FT_Glyph_To_Bitmap(&glyph, renderMode, 0, 1); if (error) { return false; } FT_BitmapGlyph bitmap = (FT_BitmapGlyph)glyph; int32_t ww = bitmap->bitmap.width; int32_t hh = bitmap->bitmap.rows; glyphInfoInit(_glyphInfo, bitmap, slot, _outBuffer, 1); FT_Done_Glyph(glyph); if (ww * hh > 0) { uint32_t dw = 6; uint32_t dh = 6; uint32_t nw = ww + dw * 2; uint32_t nh = hh + dh * 2; BX_CHECK(nw * nh < 128 * 128, "Buffer overflow (size %d)", nw * nh); uint32_t buffSize = nw * nh * sizeof(uint8_t); uint8_t* alphaImg = (uint8_t*)malloc(buffSize); memset(alphaImg, 0, nw * nh * sizeof(uint8_t) ); //copy the original buffer to the temp one for (uint32_t ii = dh; ii < nh - dh; ++ii) { memcpy(alphaImg + ii * nw + dw, _outBuffer + (ii - dh) * ww, ww); } makeDistanceMap(alphaImg, _outBuffer, nw, nh); free(alphaImg); _glyphInfo.offset_x -= (float)dw; _glyphInfo.offset_y -= (float)dh; _glyphInfo.width = (float)nw; _glyphInfo.height = (float)nh; } return true; }
///Create a display list corresponding to the given character. ///glyph_id = actual font glyph id (32 bits), ch = id for printing to screen (16 bits) void font_data::make_dlist(uint glyph_id, ushort ch) { // get the texture reference m.alloc(ch); GLuint tex = m.get_t(ch); // Translate Win-1252 with additions to Unicode if (remapflag) { if (glyph_id >= 16 && glyph_id < 32) glyph_id = unichar_low[glyph_id-16]; else if (glyph_id >= 128 && glyph_id < 160) glyph_id = unichar_high[glyph_id-128]; } // Load the Glyph for our character. if (FT_Load_Glyph(face, FT_Get_Char_Index(face, glyph_id), FT_LOAD_DEFAULT)) throw std::runtime_error("FT_Load_Glyph failed"); // Move the face's glyph into a Glyph object. FT_Glyph glyph; if (FT_Get_Glyph(face->glyph, &glyph)) throw std::runtime_error("FT_Get_Glyph failed"); // Convert the glyph to a bitmap. FT_Glyph_To_Bitmap(&glyph, ft_render_mode_normal, 0, 1); FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph) glyph; // This reference will make accessing the bitmap easier FT_Bitmap& bitmap=bitmap_glyph->bitmap; // Use our helper function to get the widths of // the bitmap data that we will need in order to create // our texture. // The max(2, ...) is used to correct for OpenGL, which // apparently does not like to have rows less than 4 bytes // long. Probably a packing thing. int width = max(2, next_p2(bitmap.width)); int height = next_p2(bitmap.rows); // Allocate memory (temporarily) for the texture data. GLubyte* expanded_data = new GLubyte[2 * width * height]; // Here we fill in the data for the expanded bitmap. // Notice that we are using two channel bitmap (one for // luminocity and one for alpha). // Luma always 255. Alpha stays alpha. // (unless of course, it is premultiplied, which in OpenGL it is not.) // We use the ?: operator so that value which we use // will be 0 if we are in the padding zone, and whatever // is the Freetype bitmap otherwise. for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { expanded_data[ 2*(i+j*width) ] = 255; expanded_data[ 2*(i+j*width)+1 ] = (i >= bitmap.width || j >= bitmap.rows) ? 0 : bitmap.buffer[i + bitmap.width*j]; } } // Now we just setup some texture paramaters. glBindTexture(GL_TEXTURE_2D, tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Here we actually create the texture itself, notice // that we are using GL_LUMINANCE_ALPHA to indicate that // we are using 2 channel data. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expanded_data); // With the texture created, we don't need the expanded data anymore delete [] expanded_data; // So now we can create the display list glNewList(list_base + ch, GL_COMPILE); glBindTexture(GL_TEXTURE_2D, tex); //glPushMatrix(); // First we need to move over a little so that // the character has the right amount of space // between it and the one before it. //glTranslatef((float) bitmap_glyph->left,0,0); // Now we move down a little in the case that the // bitmap extends past the bottom of the line // (this is only true for characters like 'g' or 'y'. //glTranslatef(0,(float)bitmap_glyph->top-bitmap.rows,0); float left_pad = (float) bitmap_glyph->left; float bot_pad = (float) bitmap.rows-bitmap_glyph->top; glTranslatef(left_pad, -bot_pad, 0); // Now we need to account for the fact that many of // our textures are filled with empty padding space. // We figure what portion of the texture is used by // the actual character and store that information in // the x and y variables, then when we draw the // quad, we will only reference the parts of the texture // that we contain the character itself. float x = (float) bitmap.width / (float) width, y = (float) bitmap.rows / (float) height; // Here we draw the texturemapped quads. // The bitmap that we got from FreeType was not // oriented quite like we would like it to be, // so we need to link the texture to the quad // so that the result will be properly aligned. glBegin(GL_QUADS); glTexCoord2d(0, 0); glVertex2f(0, (float) bitmap.rows); glTexCoord2d(0, y); glVertex2f(0, 0); glTexCoord2d(x, y); glVertex2f((float) bitmap.width, 0); glTexCoord2d(x, 0); glVertex2f((float) bitmap.width, (float) bitmap.rows); glEnd(); //glPopMatrix(); // Get width, round, and translate short ch_width = (short)(face->glyph->linearHoriAdvance >> 16); if (face->glyph->linearHoriAdvance & 0x8000) ++ch_width; //glTranslatef(ch_width, 0, 0); glTranslatef(ch_width-left_pad, bot_pad, 0); // The two ways to do width: // face->glyph->linearHoriAdvance >> 16 // face->glyph->advance.x >> 6 // Finish the display list glEndList(); // Store the width of this character m.set_w(ch, ch_width); }
static FT_Error Load_Glyph( TTF_Font* font, Uint16 ch, c_glyph* cached, int want ) { FT_Face face; FT_Error error; FT_GlyphSlot glyph; FT_Glyph_Metrics* metrics; FT_Outline* outline; if ( !font || !font->face ) { return FT_Err_Invalid_Handle; } face = font->face; /* Load the glyph */ if ( ! cached->index ) { cached->index = FT_Get_Char_Index( face, ch ); } error = FT_Load_Glyph( face, cached->index, FT_LOAD_DEFAULT | font->hinting); if( error ) { return error; } /* Get our glyph shortcuts */ glyph = face->glyph; metrics = &glyph->metrics; outline = &glyph->outline; /* Get the glyph metrics if desired */ if ( (want & CACHED_METRICS) && !(cached->stored & CACHED_METRICS) ) { if ( FT_IS_SCALABLE( face ) ) { /* Get the bounding box */ cached->minx = FT_FLOOR(metrics->horiBearingX); cached->maxx = cached->minx + FT_CEIL(metrics->width); cached->maxy = FT_FLOOR(metrics->horiBearingY); cached->miny = cached->maxy - FT_CEIL(metrics->height); cached->yoffset = font->ascent - cached->maxy; cached->advance = FT_CEIL(metrics->horiAdvance); } else { /* Get the bounding box for non-scalable format. * Again, freetype2 fills in many of the font metrics * with the value of 0, so some of the values we * need must be calculated differently with certain * assumptions about non-scalable formats. * */ cached->minx = FT_FLOOR(metrics->horiBearingX); cached->maxx = cached->minx + FT_CEIL(metrics->horiAdvance); cached->maxy = FT_FLOOR(metrics->horiBearingY); cached->miny = cached->maxy - FT_CEIL(face->available_sizes[font->font_size_family].height); cached->yoffset = 0; cached->advance = FT_CEIL(metrics->horiAdvance); } /* Adjust for bold and italic text */ if( TTF_HANDLE_STYLE_BOLD(font) ) { cached->maxx += font->glyph_overhang; } if( TTF_HANDLE_STYLE_ITALIC(font) ) { cached->maxx += (int)ceil(font->glyph_italics); } cached->stored |= CACHED_METRICS; } if ( ((want & CACHED_BITMAP) && !(cached->stored & CACHED_BITMAP)) || ((want & CACHED_PIXMAP) && !(cached->stored & CACHED_PIXMAP)) ) { int mono = (want & CACHED_BITMAP); int i; FT_Bitmap* src; FT_Bitmap* dst; FT_Glyph bitmap_glyph = NULL; /* Handle the italic style */ if( TTF_HANDLE_STYLE_ITALIC(font) ) { FT_Matrix shear; shear.xx = 1 << 16; shear.xy = (int) ( font->glyph_italics * ( 1 << 16 ) ) / font->height; shear.yx = 0; shear.yy = 1 << 16; FT_Outline_Transform( outline, &shear ); } /* Render as outline */ if( (font->outline > 0) && glyph->format != FT_GLYPH_FORMAT_BITMAP ) { FT_Stroker stroker; FT_Get_Glyph( glyph, &bitmap_glyph ); error = FT_Stroker_New( library, &stroker ); if( error ) { return error; } FT_Stroker_Set( stroker, font->outline * 64, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0 ); FT_Glyph_Stroke( &bitmap_glyph, stroker, 1 /* delete the original glyph */ ); FT_Stroker_Done( stroker ); /* Render the glyph */ error = FT_Glyph_To_Bitmap( &bitmap_glyph, mono ? ft_render_mode_mono : ft_render_mode_normal, 0, 1 ); if( error ) { FT_Done_Glyph( bitmap_glyph ); return error; } src = &((FT_BitmapGlyph)bitmap_glyph)->bitmap; } else { /* Render the glyph */ error = FT_Render_Glyph( glyph, mono ? ft_render_mode_mono : ft_render_mode_normal ); if( error ) { return error; } src = &glyph->bitmap; } /* Copy over information to cache */ if ( mono ) { dst = &cached->bitmap; } else { dst = &cached->pixmap; } memcpy( dst, src, sizeof( *dst ) ); /* FT_Render_Glyph() and .fon fonts always generate a * two-color (black and white) glyphslot surface, even * when rendered in ft_render_mode_normal. */ /* FT_IS_SCALABLE() means that the font is in outline format, * but does not imply that outline is rendered as 8-bit * grayscale, because embedded bitmap/graymap is preferred * (see FT_LOAD_DEFAULT section of FreeType2 API Reference). * FT_Render_Glyph() canreturn two-color bitmap or 4/16/256- * color graymap according to the format of embedded bitmap/ * graymap. */ if ( src->pixel_mode == FT_PIXEL_MODE_MONO ) { dst->pitch *= 8; } else if ( src->pixel_mode == FT_PIXEL_MODE_GRAY2 ) { dst->pitch *= 4; } else if ( src->pixel_mode == FT_PIXEL_MODE_GRAY4 ) { dst->pitch *= 2; } /* Adjust for bold and italic text */ if( TTF_HANDLE_STYLE_BOLD(font) ) { int bump = font->glyph_overhang; dst->pitch += bump; dst->width += bump; } if( TTF_HANDLE_STYLE_ITALIC(font) ) { int bump = (int)ceil(font->glyph_italics); dst->pitch += bump; dst->width += bump; } if (dst->rows != 0) { dst->buffer = (unsigned char *)malloc( dst->pitch * dst->rows ); if( !dst->buffer ) { return FT_Err_Out_Of_Memory; } memset( dst->buffer, 0, dst->pitch * dst->rows ); for( i = 0; i < src->rows; i++ ) { int soffset = i * src->pitch; int doffset = i * dst->pitch; if ( mono ) { unsigned char *srcp = src->buffer + soffset; unsigned char *dstp = dst->buffer + doffset; int j; if ( src->pixel_mode == FT_PIXEL_MODE_MONO ) { for ( j = 0; j < src->width; j += 8 ) { unsigned char c = *srcp++; *dstp++ = (c&0x80) >> 7; c <<= 1; *dstp++ = (c&0x80) >> 7; c <<= 1; *dstp++ = (c&0x80) >> 7; c <<= 1; *dstp++ = (c&0x80) >> 7; c <<= 1; *dstp++ = (c&0x80) >> 7; c <<= 1; *dstp++ = (c&0x80) >> 7; c <<= 1; *dstp++ = (c&0x80) >> 7; c <<= 1; *dstp++ = (c&0x80) >> 7; } } else if ( src->pixel_mode == FT_PIXEL_MODE_GRAY2 ) { for ( j = 0; j < src->width; j += 4 ) { unsigned char c = *srcp++; *dstp++ = (((c&0xA0) >> 6) >= 0x2) ? 1 : 0; c <<= 2; *dstp++ = (((c&0xA0) >> 6) >= 0x2) ? 1 : 0; c <<= 2; *dstp++ = (((c&0xA0) >> 6) >= 0x2) ? 1 : 0; c <<= 2; *dstp++ = (((c&0xA0) >> 6) >= 0x2) ? 1 : 0; } } else if ( src->pixel_mode == FT_PIXEL_MODE_GRAY4 ) { for ( j = 0; j < src->width; j += 2 ) { unsigned char c = *srcp++; *dstp++ = (((c&0xF0) >> 4) >= 0x8) ? 1 : 0; c <<= 4; *dstp++ = (((c&0xF0) >> 4) >= 0x8) ? 1 : 0; } } else { for ( j = 0; j < src->width; j++ ) {
// ----------------------------------------------- texture_font_load_glyphs --- size_t texture_font_load_glyphs( texture_font_t * self, const wchar_t * charcodes ) { assert( self ); assert( charcodes ); size_t i, x, y, width, height, depth, w, h; FT_Library library; FT_Error error; FT_Face face; FT_Glyph ft_glyph; FT_GlyphSlot slot; FT_Bitmap ft_bitmap; FT_UInt glyph_index; texture_glyph_t *glyph; ivec4 region; size_t missed = 0; width = self->atlas->width; height = self->atlas->height; depth = self->atlas->depth; region.x=1; region.y=1; #ifdef RENDERSTRING stringwidth=0; stringheight=0; stringshift=0; #endif if( !texture_font_load_face( &library, self->filename, self->size, &face ) ) { return wcslen(charcodes); } /* Load each glyph */ for( i=0; i<wcslen(charcodes); ++i ) { glyph_index = FT_Get_Char_Index( face, charcodes[i] ); // WARNING: We use texture-atlas depth to guess if user wants // LCD subpixel rendering FT_Int32 flags = 0; if( self->outline_type > 0 ) { flags |= FT_LOAD_NO_BITMAP; } else { flags |= FT_LOAD_RENDER; } if( !self->hinting ) { flags |= FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT; } else { flags |= FT_LOAD_FORCE_AUTOHINT; } if( depth == 3 ) { FT_Library_SetLcdFilter( library, FT_LCD_FILTER_LIGHT ); flags |= FT_LOAD_TARGET_LCD; if( self->filtering ) { // FT_Library_SetLcdFilterWeights( library, self->lcd_weights ); } } error = FT_Load_Glyph( face, glyph_index, flags ); if( error ) { fprintf( stderr, "FT_Error (line %d, code 0x%02x) : %s\n", __LINE__, FT_Errors[error].code, FT_Errors[error].message ); FT_Done_FreeType( library ); return wcslen(charcodes)-i; } int ft_bitmap_width = 0; int ft_bitmap_rows = 0; int ft_bitmap_pitch = 0; int ft_glyph_top = 0; int ft_glyph_left = 0; if( self->outline_type == 0 ) { slot = face->glyph; ft_bitmap = slot->bitmap; ft_bitmap_width = slot->bitmap.width; ft_bitmap_rows = slot->bitmap.rows; ft_bitmap_pitch = slot->bitmap.pitch; ft_glyph_top = slot->bitmap_top; ft_glyph_left = slot->bitmap_left; } else { FT_Stroker stroker; error = FT_Stroker_New( library, &stroker ); if( error ) { fprintf(stderr, "FT_Error (0x%02x) : %s\n", FT_Errors[error].code, FT_Errors[error].message); return 0; } FT_Stroker_Set( stroker, (int)(self->outline_thickness *64), FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); error = FT_Get_Glyph( face->glyph, &ft_glyph); if( error ) { fprintf(stderr, "FT_Error (0x%02x) : %s\n", FT_Errors[error].code, FT_Errors[error].message); return 0; } if( self->outline_type == 1 ) { error = FT_Glyph_Stroke( &ft_glyph, stroker, 1 ); } else if ( self->outline_type == 2 ) { error = FT_Glyph_StrokeBorder( &ft_glyph, stroker, 0, 1 ); } else if ( self->outline_type == 3 ) { error = FT_Glyph_StrokeBorder( &ft_glyph, stroker, 1, 1 ); } if( error ) { fprintf(stderr, "FT_Error (0x%02x) : %s\n", FT_Errors[error].code, FT_Errors[error].message); return 0; } if( depth == 1) { error = FT_Glyph_To_Bitmap( &ft_glyph, FT_RENDER_MODE_NORMAL, 0, 1); if( error ) { fprintf(stderr, "FT_Error (0x%02x) : %s\n", FT_Errors[error].code, FT_Errors[error].message); return 0; } } else { error = FT_Glyph_To_Bitmap( &ft_glyph, FT_RENDER_MODE_LCD, 0, 1); if( error ) { fprintf(stderr, "FT_Error (0x%02x) : %s\n", FT_Errors[error].code, FT_Errors[error].message); return 0; } } FT_BitmapGlyph ft_bitmap_glyph = (FT_BitmapGlyph) ft_glyph; ft_bitmap = ft_bitmap_glyph->bitmap; ft_bitmap_width = ft_bitmap.width; ft_bitmap_rows = ft_bitmap.rows; ft_bitmap_pitch = ft_bitmap.pitch; ft_glyph_top = ft_bitmap_glyph->top; ft_glyph_left = ft_bitmap_glyph->left; FT_Stroker_Done(stroker); } // We want each glyph to be separated by at least one black pixel // (for example for shader used in demo-subpixel.c) w = ft_bitmap_width/depth + 1; h = ft_bitmap_rows + 1; #ifdef RENDERSTRING static size_t maxh=0; if (charcodes[i]==13) { stringshift+=maxh+1; region.x=1; } if (h>maxh) maxh=h; //region.y=stringshift+maxh-h+1+(h-ft_glyph_top); region.y=stringshift+maxh-ft_glyph_top+1; // if (stringshift+h+h-ft_glyph_top+1>stringheight) stringheight=stringshift+h+h-ft_glyph_top+1; if (region.y+h>stringheight) stringheight=region.y+h; if (region.x+w>stringwidth) stringwidth=region.x+w; // if (region.y>=height) { missed++; continue; } // if (region.x+w>=width) {missed++; continue; } // if (h+h-ft_glyph_top+1>=height) { missed++; continue; } // if (h+h-ft_glyph_top+2>=height) { missed++; continue; } // if (region.y+maxh>=height) { missed++; continue; } #else region = texture_atlas_get_region( self->atlas, w, h ); if ( region.x < 0 ) { missed++; // fprintf( stderr, "Texture atlas is full (line %d)\n", __LINE__ ); continue; } #endif w = w - 1; h = h - 1; x = region.x; y = region.y; if (charcodes[i]!=13) { #ifdef RENDERSTRING if (!(x<width)||!((x+w)<=width)||!(y<height)||!((y+h)<=height)) { missed++; continue; } #endif texture_atlas_set_region( self->atlas, x, y, w, h, ft_bitmap.buffer, ft_bitmap.pitch ); } glyph = texture_glyph_new( ); glyph->charcode = charcodes[i]; glyph->width = w; glyph->height = h; glyph->outline_type = self->outline_type; glyph->outline_thickness = self->outline_thickness; glyph->offset_x = ft_glyph_left; glyph->offset_y = ft_glyph_top; glyph->s0 = x/(float)width; glyph->t0 = y/(float)height; glyph->s1 = (x + glyph->width)/(float)width; glyph->t1 = (y + glyph->height)/(float)height; // Discard hinting to get advance FT_Load_Glyph( face, glyph_index, FT_LOAD_RENDER | FT_LOAD_NO_HINTING); slot = face->glyph; glyph->advance_x = slot->advance.x/64.0; glyph->advance_y = slot->advance.y/64.0; #ifdef RENDERSTRING if (charcodes[i]!=13) region.x+=(int)glyph->advance_x; #endif vector_push_back( self->glyphs, &glyph ); } if( self->outline_type > 0 ) { FT_Done_Glyph( ft_glyph ); } FT_Done_Face( face ); FT_Done_FreeType( library ); // texture_atlas_upload( self->atlas ); texture_font_generate_kerning( self ); return missed; }
long EMSCRIPTEN_KEEPALIVE c_Glyph_toBitmap(long glyph, int renderMode) { FT_Glyph bitmap = (FT_Glyph)glyph; FT_Error error = FT_Glyph_To_Bitmap(&bitmap, (FT_Render_Mode)renderMode, NULL, 1); if(error) return 0; return (long)bitmap; }
/** 转换FT_GlyphSlot类型数据为LCUI_FontBMP */ static int Convert_FTGlyph( LCUI_FontBMP *bmp, FT_GlyphSlot slot, int mode ) { int error; size_t size; FT_BitmapGlyph bitmap_glyph; FT_Glyph glyph; /* 从字形槽中提取一个字形图像 * 请注意,创建的FT_Glyph对象必须与FT_Done_Glyph成对使用 */ error = FT_Get_Glyph( slot, &glyph ); if(error) { return -1; } /*---------------------- 打印字体信息 -------------------------- printf(" width= %ld, met->height= %ld\n" "horiBearingX = %ld, horiBearingY = %ld, horiAdvance = %ld\n" "vertBearingX = %ld, vertBearingY = %ld, vertAdvance = %ld\n", slot->metrics.width>>6, slot->metrics.height>>6, slot->metrics.horiBearingX>>6, slot->metrics.horiBearingY>>6, slot->metrics.horiAdvance>>6, slot->metrics.vertBearingX>>6, slot->metrics.vertBearingY>>6, slot->metrics.vertAdvance>>6 ); ------------------------------------------------------------*/ if ( glyph->format != FT_GLYPH_FORMAT_BITMAP ) { error = FT_Glyph_To_Bitmap(&glyph, mode, 0 ,1); if(error) { return -1; } } bitmap_glyph = (FT_BitmapGlyph)glyph; /* * FT_Glyph_Metrics结构体中保存字形度量,通过face->glyph->metrics结 * 构访问,可得到字形的宽、高、左边界距、上边界距、水平跨距等等。 * 注意:因为不是所有的字体都包含垂直度量,当FT_HAS_VERTICAL为假时, * vertBearingX,vertBearingY和vertAdvance的值是不可靠的,目前暂不考虑 * 此情况的处理。 * */ bmp->top = bitmap_glyph->top; bmp->left = slot->metrics.horiBearingX>>6; bmp->rows = bitmap_glyph->bitmap.rows; bmp->width = bitmap_glyph->bitmap.width; bmp->advance.x = slot->metrics.horiAdvance>>6; /* 水平跨距 */ bmp->advance.y = slot->metrics.vertAdvance>>6; /* 垂直跨距 */ /* 分配内存,用于保存字体位图 */ size = bmp->rows * bmp->width * sizeof(uchar_t); bmp->buffer = (uchar_t*)malloc( size ); if( !bmp->buffer ) { FT_Done_Glyph(glyph); return -1; } switch( bitmap_glyph->bitmap.pixel_mode ) { /* 8位灰度位图,直接拷贝 */ case FT_PIXEL_MODE_GRAY: memcpy( bmp->buffer, bitmap_glyph->bitmap.buffer, size ); break; /* 单色点阵图,需要转换 */ case FT_PIXEL_MODE_MONO: { FT_Bitmap bitmap; FT_Library lib; FT_Int x, y; uchar_t *t, *s; lib = FontLIB_GetLibrary(); FT_Bitmap_New( &bitmap ); /* 转换位图bitmap_glyph->bitmap至bitmap,1个像素占1个字节 */ FT_Bitmap_Convert( lib, &bitmap_glyph->bitmap, &bitmap, 1); s = bitmap.buffer; t = bmp->buffer; for( y=0; y<bmp->rows; ++y ) { for( x=0; x<bmp->width; ++x ) { *t = *s?255:0; ++t,++s; } } FT_Bitmap_Done( lib, &bitmap ); break; } /* 其它像素模式的位图,暂时先直接填充255,等需要时再完善 */ default: memset( bmp->buffer, 255, size ); break; } FT_Done_Glyph(glyph); return size; }
void freetype_genFontTexture_ascii(FT_Face face, c_font *gameFont, unsigned int pixel_height) { const unsigned int glyphsToRender = 256; // ASCII set, change at your peril GLubyte *pixel_data; unsigned int glyph_pixel_width = 0; unsigned int glyph_pixel_height = 0; unsigned int texture_width = 0; unsigned int texture_height = 0; FT_Glyph glyphArray[glyphsToRender]; FT_BitmapGlyph bitmapGlyphArray[glyphsToRender]; unsigned int lv; // loop variable // first loop through glyphs to determine how big the bigest one is. for (lv=0 ; lv<glyphsToRender ; lv++) { int error; error = FT_Load_Glyph(face, FT_Get_Char_Index( face, lv), FT_LOAD_DEFAULT); if (error) { printf("FT_Load_Glyph [%u] ", error); } error = FT_Get_Glyph( face->glyph, &glyphArray[lv] ); if (error) { printf("FT_Get_Glyph [%u] ", error); } FT_Glyph_To_Bitmap( &glyphArray[lv], ft_render_mode_normal, 0, 1 ); bitmapGlyphArray[lv] = (FT_BitmapGlyph)glyphArray[lv]; FT_Bitmap& bitmap = bitmapGlyphArray[lv]->bitmap; if ((unsigned int)bitmap.rows > glyph_pixel_height) glyph_pixel_height = bitmap.rows; if ((unsigned int)bitmap.width > glyph_pixel_width) glyph_pixel_width = bitmap.width; } // make sure each glyph is a power of 2 // not 100% necessary, but if we want each glyph to have an equal percentage // of texture space we better do it. glyph_pixel_width = next_power_of_2(glyph_pixel_width); glyph_pixel_height = next_power_of_2(glyph_pixel_height); // now all glyph specs are pretty much finalized (so lets brag about it) printf(" character size: %ux%u, ", glyph_pixel_width, glyph_pixel_height); texture_width = glyph_pixel_width * 16; texture_height = glyph_pixel_height * 16; printf("ascii texture size: %ux%u\n", texture_width, texture_height); // make some pixel data in ram (this will be the font texture) unsigned int bytesForImage = 2 * texture_width * texture_height; pixel_data = new GLubyte[bytesForImage]; // zero out all the newly allocated data for (unsigned int clearloop=0 ; clearloop < bytesForImage ; clearloop++ ) { pixel_data[clearloop] = 0; } unsigned int glyphX_start = 0; unsigned int glyphY_start = 0; // now to go through each glyph again for (lv=0 ; lv<glyphsToRender ; lv++ ) { FT_Bitmap& bitmap = bitmapGlyphArray[lv]->bitmap; glyphX_start = lv % 16; glyphY_start = lv / 16; glyphX_start *= glyph_pixel_width; glyphY_start *= glyph_pixel_height; // draw glyph out in the correct spot on the 16x16 glyph texture for(unsigned int gx=0; gx< (unsigned int)bitmap.width; gx++) { for(unsigned int gy=0; gy< (unsigned int)bitmap.rows ; gy++) { unsigned char *byte_luminence; unsigned char *byte_alpha; // calculate which pixels to work on unsigned int pixel_mem_loc = 2 * ( // channels: luminence & alpha texture_width * (glyphY_start + gy) + glyphX_start + gx ); byte_luminence = &pixel_data[ pixel_mem_loc ]; byte_alpha = &pixel_data[ pixel_mem_loc + 1 ]; *byte_luminence = 255; // or this if you'd rather do this to blacken the alpha edges: bitmap.buffer[gx + bitmap.width * gy]; *byte_alpha = bitmap.buffer[gx + bitmap.width * gy]; } } // pixel coordinates for glyph unsigned int top = (lv / 16) * glyph_pixel_height; unsigned int left = (lv % 16) * glyph_pixel_width; unsigned int bottom = top + bitmap.rows; unsigned int right = left + bitmap.width; // texture coordinates for glyph float uv_top = (float)top / texture_height; float uv_left = (float)left / texture_width; float uv_bottom = (float)bottom / texture_height; float uv_right = (float)right / texture_width; // seems some letters get cut too short to see their nice anti-aliasing - should probably do this when rendering // but then again it's probably a single pixel of low alpha that's getting cut so it may be best to do a single // pixel pad here, on the left and right sides. uv_top -= 1 * (1.0f / texture_height); uv_left -= 1 * (1.0f / texture_width); uv_bottom += 1 * (1.0f / texture_height); uv_right += 1 * (1.0f / texture_width); ////////////////////////////////////////////////////////////////// // actually assign this data to the class gameFont->glyph[lv].set_uv(pixel_height, texture_width, texture_height, uv_top, uv_left, uv_bottom, uv_right); // figure out how much to lower characters that hang below the line float shift_y = (float)bitmap.rows - (float)bitmapGlyphArray[lv]->top; shift_y /= texture_height; gameFont->glyph[lv].set_shift(pixel_height, texture_height, shift_y); // set the advance - not used yet //face->glyph->advance; float advance = glyphArray[lv]->advance.x; gameFont->glyph[lv].set_advance(pixel_height, texture_width, advance); // test to see if glyph uv coordinates are what they should be /*if (lv == (unsigned int)'g') { printf("%c - uv(t=%f, l=%f, b=%f, r=%f) - shift(y=%f) - advance(x=%f)\n", (char)lv, gameFont->glyph[lv].uv_top(), gameFont->glyph[lv].uv_left(), gameFont->glyph[lv].uv_bottom(), gameFont->glyph[lv].uv_right(), gameFont->glyph[lv].shift_y(), gameFont->glyph[lv].advance_x()); }*/ } glGenTextures(1, &gameFont->opengl_texture_id); glBindTexture( GL_TEXTURE_2D, gameFont->opengl_texture_id); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); //Here we actually create the texture itself, notice //that we are using GL_LUMINANCE_ALPHA to indicate that //we are using 2 channel data. //glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, texture_width, texture_height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, pixel_data ); // do that line above - or build some mipmaps for trilinear filtering gluBuild2DMipmaps( GL_TEXTURE_2D, GL_LUMINANCE_ALPHA, texture_width, texture_height, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, pixel_data ); //printf("texture specs: %ux%u\n", wsf, height); // now that all of that the image has been loading into the // graphics card, we can free up the copy we built in the ram delete pixel_data; }
static int LayoutLine( filter_t *p_filter, paragraph_t *p_paragraph, int i_start_offset, int i_end_offset, line_desc_t **pp_line ) { if( p_paragraph->i_size <= 0 || p_paragraph->i_runs_count <= 0 || i_start_offset >= i_end_offset || i_start_offset < 0 || i_start_offset >= p_paragraph->i_size || i_end_offset <= 0 || i_end_offset > p_paragraph->i_size ) { msg_Err( p_filter, "LayoutLine() invalid parameters. " "Paragraph size: %d. Runs count: %d. " "Start offset: %d. End offset: %d", p_paragraph->i_size, p_paragraph->i_runs_count, i_start_offset, i_end_offset ); return VLC_EGENERIC; } line_desc_t *p_line = NewLine( i_end_offset - i_start_offset ); if( !p_line ) return VLC_ENOMEM; filter_sys_t *p_sys = p_filter->p_sys; int i_last_run = -1; run_desc_t *p_run = 0; text_style_t *p_style = 0; FT_Face p_face = 0; FT_Vector pen = { .x = 0, .y = 0 }; int i_line_index = 0; int i_font_width = 0; int i_ul_offset = 0; int i_ul_thickness = 0; #ifdef HAVE_FRIBIDI fribidi_reorder_line( 0, p_paragraph->p_types + i_start_offset, i_end_offset - i_start_offset, 0, p_paragraph->paragraph_type, p_paragraph->p_levels + i_start_offset, 0, p_paragraph->pi_reordered_indices + i_start_offset ); #endif for( int i = i_start_offset; i < i_end_offset; ++i, ++i_line_index ) { int i_paragraph_index; #ifdef HAVE_FRIBIDI i_paragraph_index = p_paragraph->pi_reordered_indices[ i ]; #else i_paragraph_index = i; #endif line_character_t *p_ch = p_line->p_character + i_line_index; glyph_bitmaps_t *p_bitmaps = p_paragraph->p_glyph_bitmaps + i_paragraph_index; if( !p_bitmaps->p_glyph ) { --i_line_index; continue; } if( i_last_run != p_paragraph->pi_run_ids[ i_paragraph_index ] ) { i_last_run = p_paragraph->pi_run_ids[ i_paragraph_index ]; p_run = p_paragraph->p_runs + i_last_run; p_style = p_run->p_style; p_face = p_run->p_face; i_font_width = p_style->i_style_flags & STYLE_HALFWIDTH ? p_style->i_font_size / 2 : p_style->i_font_size; } FT_Vector pen_new = { .x = pen.x + p_paragraph->p_glyph_bitmaps[ i_paragraph_index ].i_x_offset, .y = pen.y + p_paragraph->p_glyph_bitmaps[ i_paragraph_index ].i_y_offset }; FT_Vector pen_shadow = { .x = pen_new.x + p_sys->f_shadow_vector_x * ( i_font_width << 6 ), .y = pen_new.y + p_sys->f_shadow_vector_y * ( p_style->i_font_size << 6 ) }; if( p_bitmaps->p_shadow ) { if( FT_Glyph_To_Bitmap( &p_bitmaps->p_shadow, FT_RENDER_MODE_NORMAL, &pen_shadow, 0 ) ) p_bitmaps->p_shadow = 0; else FT_Glyph_Get_CBox( p_bitmaps->p_shadow, ft_glyph_bbox_pixels, &p_bitmaps->shadow_bbox ); } if( p_bitmaps->p_glyph ) { if( FT_Glyph_To_Bitmap( &p_bitmaps->p_glyph, FT_RENDER_MODE_NORMAL, &pen_new, 1 ) ) { FT_Done_Glyph( p_bitmaps->p_glyph ); if( p_bitmaps->p_outline ) FT_Done_Glyph( p_bitmaps->p_outline ); if( p_bitmaps->p_shadow ) FT_Done_Glyph( p_bitmaps->p_shadow ); --i_line_index; continue; } else FT_Glyph_Get_CBox( p_bitmaps->p_glyph, ft_glyph_bbox_pixels, &p_bitmaps->glyph_bbox ); } if( p_bitmaps->p_outline ) { if( FT_Glyph_To_Bitmap( &p_bitmaps->p_outline, FT_RENDER_MODE_NORMAL, &pen_new, 1 ) ) { FT_Done_Glyph( p_bitmaps->p_outline ); p_bitmaps->p_outline = 0; } else FT_Glyph_Get_CBox( p_bitmaps->p_outline, ft_glyph_bbox_pixels, &p_bitmaps->outline_bbox ); } FixGlyph( p_bitmaps->p_glyph, &p_bitmaps->glyph_bbox, p_bitmaps->i_x_advance, p_bitmaps->i_y_advance, &pen_new ); if( p_bitmaps->p_outline ) FixGlyph( p_bitmaps->p_outline, &p_bitmaps->outline_bbox, p_bitmaps->i_x_advance, p_bitmaps->i_y_advance, &pen_new ); if( p_bitmaps->p_shadow ) FixGlyph( p_bitmaps->p_shadow, &p_bitmaps->shadow_bbox, p_bitmaps->i_x_advance, p_bitmaps->i_y_advance, &pen_shadow ); int i_line_offset = 0; int i_line_thickness = 0; text_style_t *p_glyph_style = p_paragraph->pp_styles[ i_paragraph_index ]; if( p_glyph_style->i_style_flags & (STYLE_UNDERLINE | STYLE_STRIKEOUT) ) { i_line_offset = abs( FT_FLOOR( FT_MulFix( p_face->underline_position, p_face->size->metrics.y_scale ) ) ); i_line_thickness = abs( FT_CEIL( FT_MulFix( p_face->underline_thickness, p_face->size->metrics.y_scale ) ) ); if( p_glyph_style->i_style_flags & STYLE_STRIKEOUT ) { /* Move the baseline to make it strikethrough instead of * underline. That means that strikethrough takes precedence */ i_line_offset -= abs( FT_FLOOR( FT_MulFix( p_face->descender * 2, p_face->size->metrics.y_scale ) ) ); } else if( i_line_thickness > 0 ) { p_bitmaps->glyph_bbox.yMin = __MIN( p_bitmaps->glyph_bbox.yMin, - i_line_offset - i_line_thickness ); /* The real underline thickness and position are * updated once the whole line has been parsed */ i_ul_offset = __MAX( i_ul_offset, i_line_offset ); i_ul_thickness = __MAX( i_ul_thickness, i_line_thickness ); i_line_thickness = -1; } } p_ch->p_glyph = ( FT_BitmapGlyph ) p_bitmaps->p_glyph; p_ch->p_outline = ( FT_BitmapGlyph ) p_bitmaps->p_outline; p_ch->p_shadow = ( FT_BitmapGlyph ) p_bitmaps->p_shadow; bool b_karaoke = p_paragraph->pi_karaoke_bar[ i_paragraph_index ] != 0; p_ch->i_color = b_karaoke ? ( uint32_t ) p_glyph_style->i_karaoke_background_color | p_glyph_style->i_karaoke_background_alpha << 24 : ( uint32_t ) p_glyph_style->i_font_color | p_glyph_style->i_font_alpha << 24; p_ch->i_line_thickness = i_line_thickness; p_ch->i_line_offset = i_line_offset; BBoxEnlarge( &p_line->bbox, &p_bitmaps->glyph_bbox ); if( p_bitmaps->p_outline ) BBoxEnlarge( &p_line->bbox, &p_bitmaps->outline_bbox ); if( p_bitmaps->p_shadow ) BBoxEnlarge( &p_line->bbox, &p_bitmaps->shadow_bbox ); pen.x += p_bitmaps->i_x_advance; pen.y += p_bitmaps->i_y_advance; } p_line->i_width = __MAX( 0, p_line->bbox.xMax - p_line->bbox.xMin ); p_line->i_height = __MAX( 0, p_line->bbox.yMax - p_line->bbox.yMin ); p_line->i_character_count = i_line_index; if( i_ul_thickness > 0 ) { for( int i = 0; i < p_line->i_character_count; i++ ) { line_character_t *ch = &p_line->p_character[i]; if( ch->i_line_thickness < 0 ) { ch->i_line_offset = i_ul_offset; ch->i_line_thickness = i_ul_thickness; } } } *pp_line = p_line; return VLC_SUCCESS; } static int LayoutParagraph( filter_t *p_filter, paragraph_t *p_paragraph, int i_max_pixel_width, line_desc_t **pp_lines ) { if( p_paragraph->i_size <= 0 || p_paragraph->i_runs_count <= 0 ) { msg_Err( p_filter, "LayoutParagraph() invalid parameters. " "Paragraph size: %d. Runs count %d", p_paragraph->i_size, p_paragraph->i_runs_count ); return VLC_EGENERIC; } int i_line_start = 0; FT_Pos i_width = 0; FT_Pos i_max_width = i_max_pixel_width << 6; FT_Pos i_preferred_width = 0; FT_Pos i_total_width = 0; FT_Pos i_last_space_width = 0; int i_last_space = -1; line_desc_t *p_first_line = 0; line_desc_t **pp_line = &p_first_line; for( int i = 0; i < p_paragraph->i_size; ++i ) { #ifdef HAVE_FRIBIDI p_paragraph->pi_reordered_indices[ i ] = i; #endif i_total_width += p_paragraph->p_glyph_bitmaps[ i ].i_x_advance; } int i_line_count = i_total_width / i_max_width + 1; i_preferred_width = i_total_width / i_line_count; for( int i = 0; i <= p_paragraph->i_size; ++i ) { if( i == p_paragraph->i_size ) { if( i_line_start < i ) if( LayoutLine( p_filter, p_paragraph, i_line_start, i, pp_line ) ) goto error; break; } if( p_paragraph->p_code_points[ i ] == ' ' #ifdef HAVE_FRIBIDI || p_paragraph->p_types[ i ] == FRIBIDI_TYPE_WS #endif ) { if( i_line_start == i ) { /* * Free orphaned white space glyphs not belonging to any lines. * At this point p_shadow points to either p_glyph or p_outline, * so we should not free it explicitly. */ if( p_paragraph->p_glyph_bitmaps[ i ].p_glyph ) FT_Done_Glyph( p_paragraph->p_glyph_bitmaps[ i ].p_glyph ); if( p_paragraph->p_glyph_bitmaps[ i ].p_outline ) FT_Done_Glyph( p_paragraph->p_glyph_bitmaps[ i ].p_outline ); i_line_start = i + 1; continue; } if( i_last_space == i - 1 ) { p_paragraph->p_glyph_bitmaps[ i - 1 ].i_x_advance = 0; i_last_space = i; continue; } i_last_space = i; i_last_space_width = i_width; } i_width += p_paragraph->p_glyph_bitmaps[ i ].i_x_advance; if( i_last_space_width >= i_preferred_width || i_width >= i_max_width ) { if( i_line_start == i ) { msg_Err( p_filter, "LayoutParagraph(): Width of single glyph exceeds maximum" ); goto error; } int i_end_offset; if( i_last_space > i_line_start ) i_end_offset = i_last_space; else i_end_offset = i; if( LayoutLine( p_filter, p_paragraph, i_line_start, i_end_offset, pp_line ) ) goto error; pp_line = &( *pp_line )->p_next; i_line_start = i_end_offset; i = i_line_start - 1; i_width = 0; i_last_space_width = 0; } } *pp_lines = p_first_line; return VLC_SUCCESS; error: for( int i = i_line_start; i < p_paragraph->i_size; ++i ) { if( p_paragraph->p_glyph_bitmaps[ i ].p_glyph ) FT_Done_Glyph( p_paragraph->p_glyph_bitmaps[ i ].p_glyph ); if( p_paragraph->p_glyph_bitmaps[ i ].p_outline ) FT_Done_Glyph( p_paragraph->p_glyph_bitmaps[ i ].p_outline ); } if( p_first_line ) FreeLines( p_first_line ); return VLC_EGENERIC; } int LayoutText( filter_t *p_filter, line_desc_t **pp_lines, FT_BBox *p_bbox, int *pi_max_face_height, uni_char_t *psz_text, text_style_t **pp_styles, uint32_t *pi_k_dates, int i_len ) { line_desc_t *p_first_line = 0; line_desc_t **pp_line = &p_first_line; paragraph_t *p_paragraph = 0; int i_paragraph_start = 0; int i_max_height = 0; for( int i = 0; i <= i_len; ++i ) { if( i == i_len || psz_text[ i ] == '\n' ) { if( i_paragraph_start == i ) { i_paragraph_start = i + 1; continue; } p_paragraph = NewParagraph( p_filter, i - i_paragraph_start, psz_text + i_paragraph_start, pp_styles + i_paragraph_start, pi_k_dates ? pi_k_dates + i_paragraph_start : 0, 20 ); if( !p_paragraph ) { if( p_first_line ) FreeLines( p_first_line ); return VLC_ENOMEM; } #ifdef HAVE_FRIBIDI if( AnalyzeParagraph( p_paragraph ) ) goto error; #endif if( ItemizeParagraph( p_filter, p_paragraph ) ) goto error; #if defined HAVE_HARFBUZZ if( ShapeParagraphHarfBuzz( p_filter, &p_paragraph ) ) goto error; if( LoadGlyphs( p_filter, p_paragraph, true, false ) ) goto error; #elif defined HAVE_FRIBIDI if( ShapeParagraphFriBidi( p_filter, p_paragraph ) ) goto error; if( LoadGlyphs( p_filter, p_paragraph, false, true ) ) goto error; if( RemoveZeroWidthCharacters( p_paragraph ) ) goto error; if( ZeroNsmAdvance( p_paragraph ) ) goto error; #else if( LoadGlyphs( p_filter, p_paragraph, false, true ) ) goto error; #endif /* * Set max line width to allow for outline and shadow glyphs, * and any extra width caused by visual reordering */ int i_max_width = ( int ) p_filter->fmt_out.video.i_visible_width - 2 * p_filter->p_sys->style.i_font_size; if( LayoutParagraph( p_filter, p_paragraph, i_max_width, pp_line ) ) goto error; FreeParagraph( p_paragraph ); p_paragraph = 0; for( ; *pp_line; pp_line = &( *pp_line )->p_next ) i_max_height = __MAX( i_max_height, ( *pp_line )->i_height ); i_paragraph_start = i + 1; } } int i_base_line = 0; FT_BBox bbox = { .xMin = INT_MAX, .yMin = INT_MAX, .xMax = INT_MIN, .yMax = INT_MIN }; for( line_desc_t *p_line = p_first_line; p_line; p_line = p_line->p_next ) { p_line->i_base_line = i_base_line; p_line->bbox.yMin -= i_base_line; p_line->bbox.yMax -= i_base_line; BBoxEnlarge( &bbox, &p_line->bbox ); i_base_line += i_max_height; } *pp_lines = p_first_line; *p_bbox = bbox; *pi_max_face_height = i_max_height; return VLC_SUCCESS; error: if( p_first_line ) FreeLines( p_first_line ); if( p_paragraph ) FreeParagraph( p_paragraph ); return VLC_EGENERIC; }
/* TODO: Font rendering MUST be redesigned. */ Font* GuiRendererD3D11::MakeFont(const char* pPath, int height) { Common::Timer timer; timer.Start(); FT_Face face; int texWidth = 4096; int texHeight = 4096; //create pixels array unsigned char* pTexData = (unsigned char*)malloc(texWidth * texHeight); ZeroMemory(pTexData, texWidth * texHeight); if (FT_New_Face(mFreeTypeLibrary, pPath, 0, &face) != 0) { free(pTexData); // TODO // LOG_ERROR("Failed to load font '%s'.", pPath); return 0; } //FT_Set_Pixel_Sizes(face, 2*height, 2*height); FT_Set_Char_Size(face, 0, height * 64, 96, 96); Font* pFont = new Font; /* FT_Matrix Transform; Transform.xx = (FT_Fixed)(1.0f * 0x10000L); Transform.xy = (FT_Fixed)(0.0f * 0x10000L); Transform.yx = (FT_Fixed)(0.0f * 0x10000L); Transform.yy = (FT_Fixed)(1.0f * 0x10000L); FT_Set_Transform(face, &Transform, 0); */ int Width; int Height; int OffsetX = 0; int OffsetY = 0; pFont->height = height; pFont->charCount = 65536; pFont->characters = (CharacterInfo*)malloc(sizeof(CharacterInfo) * pFont->charCount); int Index = 0; for (int ChrId = 0; ChrId < (65536); ChrId++) { // Load The Glyph For Our Character. unsigned int GlyphIndex = FT_Get_Char_Index(face, ChrId); if (GlyphIndex == 0) { pFont->characters[ChrId].exists = false; continue; } FT_Load_Glyph(face, GlyphIndex, FT_LOAD_DEFAULT); // Move The Face's Glyph Into A Glyph Object. FT_Glyph glyph; FT_Get_Glyph(face->glyph, &glyph); // Convert The Glyph To A Bitmap. FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1); FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph; // This Reference Will Make Accessing The Bitmap Easier. FT_Bitmap& bitmap = bitmap_glyph->bitmap; Width = bitmap.width; Height = bitmap.rows; //char won't fit to texture if (OffsetX + Width + 2 > texWidth) { OffsetX = 0; OffsetY += 2 * height; } for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { unsigned char Value = bitmap.buffer[x + Width * y]; int PxOffset = (y + OffsetY) * texWidth + x + OffsetX; pTexData[PxOffset] = Value; } } pFont->characters[ChrId].exists = true; pFont->characters[ChrId].top = (short)bitmap_glyph->top; pFont->characters[ChrId].left = (short)bitmap_glyph->left; pFont->characters[ChrId].height = (short)Height; pFont->characters[ChrId].width = (short)Width; pFont->characters[ChrId].u = (short)OffsetX; pFont->characters[ChrId].v = (short)OffsetY; pFont->characters[ChrId].spacing = (short)(face->glyph->advance.x >> 6) + 1; FT_Done_Glyph(glyph); OffsetX += pFont->characters[ChrId].width + 1; Index++; } //close font FT_Done_Face(face); OffsetY += 2 * height; // Used texture height texHeight = CeilToPowerOf2(OffsetY); Common::Image fontImage; fontImage.SetData(pTexData, texWidth, texHeight, Common::ImageFormat::A_UBYTE); // pFont->texture = pRenderer->CreateTexture(&fontImage, false); pFont->texture = new RendererTextureD3D11; pFont->texture->FromImage(fontImage); pFont->texHeight = texHeight; pFont->texWidth = texWidth; free(pTexData); // TODO // LOG_SUCCESS("Font '%s', size %i loaded in %.3lf seconds.", pPath, height, timer.Stop()); return pFont; }
/* * Renders a glyph immediately, then tries to puts it into cache. * rend and rend->face must be not 0 */ static GLYPH* _gk_rend_workout(GLYPH_REND* const rend,const unsigned unicode) { unsigned glyph_index; int bmp_size; int error; int center_x = 0,center_y = 0; FT_Glyph ft_glyph = 0; GLYPH* glyph; GLYPH_FACE* actual_face; unsigned actual_code; #ifdef GLYPH_LOG if (glyph_log) fprintf(glyph_log,"_gk_rend_workout(%p,%d) begin\n",(void*)rend,unicode); #endif CARE(rend && rend->face); CARE(unicode > 0); CARE(unicode <= GK_MAX_UNICODE); funcname = "_gk_rend_workout()"; _gk_find_mapping(rend->face,unicode,&actual_face,&actual_code); if (!actual_face || !actual_code) return 0; if (!actual_face->face) return 0; glyph_index = FT_Get_Char_Index(actual_face->face,actual_code); if (!glyph_index) { if (unicode==rend->undefined_char || unicode==rend->error_char) return 0; else return _gk_rend_render(rend,rend->undefined_char); } #ifdef GLYPH_LOG if (glyph_log) fprintf(glyph_log," glyph_index is %u\n",glyph_index); #endif /* Preparing for glyph loading: setting size */ /*FT_Activate_Size(size);*/ if (actual_face == rend->face) { error = (rend->size == 0); if (!error) actual_face->face->size = rend->size; } else { error = (actual_face->own_size == 0); if (!error) { actual_face->face->size = actual_face->own_size; error = FT_Set_Char_Size(actual_face->face,rend->hsize,rend->vsize,72,72); } } #ifdef GLYPH_LOG if (error) { if (glyph_log) fprintf(glyph_log," Failed to select size\n"); } else { if (glyph_log) fprintf(glyph_log," Size selected successfully\n"); } #endif /* Loading a glyph with FreeType */ if (!error) { error = FT_Load_Glyph(actual_face->face,glyph_index,rend->load_flags); if (error) _gk_msg("Error: %s: FT_Load_Glyph() bugs on glyph (#%d) for character U+%04X\n",funcname,glyph_index,unicode); else { error = (actual_face->face->glyph == 0); if (error) _gk_msg("Error: %s: Empty glyph slot after FT_Load_Glyph()\n",funcname); } /*#ifdef GLYPH_LOG if (error) { if (glyph_log) fprintf(glyph_log," Could not load a glyph with FT_Load_Glyph()\n"); } else { if (glyph_log) fprintf(glyph_log," Loaded a glyph with FT_Load_Glyph()\n"); } #endif*/ } /* Getting center coordinates (MEGA-HACK) */ /* This whole idea should be re-made in more optimal way */ if (!error) { /*#ifdef GLYPH_LOG if (glyph_log) fprintf(glyph_log," Getting a center point\n"); #endif*/ FT_Glyph g = 0; error = FT_Get_Glyph(actual_face->face->glyph, &g); /*#ifdef GLYPH_LOG if (glyph_log) { if (error) fprintf(glyph_log," FT_Get_Glyph() failed\n"); else fprintf(glyph_log," FT_Get_Glyph() succeeded\n"); if (g) fprintf(glyph_log," FT_Get_Glyph() returned not 0\n"); else fprintf(glyph_log," FT_Get_Glyph() returned 0\n"); } #endif*/ error = error || !g; if (!error && g->format==FT_GLYPH_FORMAT_OUTLINE) { /*#ifdef GLYPH_LOG if (glyph_log) fprintf(glyph_log," Calling FT_Glyph_To_Bitmap()\n"); #endif*/ error = FT_Glyph_To_Bitmap(&g,rend->render_mode,0,1); /*#ifdef GLYPH_LOG if (glyph_log) { if (error) fprintf(glyph_log," FT_Glyph_To_Bitmap() failed\n"); else fprintf(glyph_log," FT_Glyph_To_Bitmap() succeeded\n"); } #endif*/ if (!error) { center_x = 64 * ((FT_BitmapGlyph)g)->left + 64 * ((FT_BitmapGlyph)g)->bitmap.width / 2; center_y = 64 * ((FT_BitmapGlyph)g)->top - 64 * ((FT_BitmapGlyph)g)->bitmap.rows / 2; /*center_x = 64 * ((FT_BitmapGlyph)g)->bitmap.width / 2; center_y = -64 * ((FT_BitmapGlyph)g)->bitmap.rows / 2;*/ } } if (g) { /*#ifdef GLYPH_LOG if (glyph_log) fprintf(glyph_log," Calling FT_Done_Glyph()\n"); #endif*/ FT_Done_Glyph(g); } /*#ifdef GLYPH_LOG if (glyph_log) { if (error) fprintf(glyph_log," Could not find a center point\n"); else fprintf(glyph_log," Computed a center point\n"); } #endif*/ } /* Emboldening the glyph */ if (!error) { if (rend->bold_strength && actual_face->face->glyph->format==FT_GLYPH_FORMAT_OUTLINE) { int xstr, ystr, xstr2, ystr2; int xmin,xmax,ymin,ymax; int center_dx, center_dy; FT_GlyphSlot slot = actual_face->face->glyph; #ifdef GLYPH_LOG if (glyph_log) fprintf(glyph_log," Emboldening the glyph by %d\n",rend->bold_strength); #endif xstr = rend->bold_strength * FT_MulFix( actual_face->face->units_per_EM, actual_face->face->size->metrics.y_scale ) / 2400; ystr = xstr; #ifdef GLYPH_LOG if (glyph_log) fprintf(glyph_log," xstr = %d, ystr = %d\n",xstr,ystr); #endif GK_Outline_Embolden(&slot->outline,xstr,&xmin,&xmax,&ymin,&ymax); #ifdef GLYPH_LOG if (glyph_log) fprintf(glyph_log," xmin = %d, xmax = %d\n",xmin,xmax); if (glyph_log) fprintf(glyph_log," ymin = %d, ymax = %d\n",ymin,ymax); #endif /*xstr = xstr * 2; ystr = xstr;*/ #ifdef GLYPH_LOG if (glyph_log) fprintf(glyph_log," xstr = %d, ystr = %d\n",xstr,ystr); #endif xstr2 = xmin+xmax; ystr2 = ymin+ymax; #ifdef GLYPH_LOG if (glyph_log) fprintf(glyph_log," xstr2 = %d, ystr2 = %d\n",xstr2,ystr2); if (glyph_log) fprintf(glyph_log," xscale = %.5f\n",((double)actual_face->face->size->metrics.x_scale)/65536); if (glyph_log) fprintf(glyph_log," yscale = %.5f\n",((double)actual_face->face->size->metrics.y_scale)/65536); #endif if (slot->advance.x) slot->advance.x += xstr; if (slot->advance.y) slot->advance.y += ystr; slot->metrics.width += xstr * 2; slot->metrics.height += ystr * 2; /*slot->metrics.horiBearingX -= xmin;*/ slot->metrics.horiBearingY += ystr * 2; slot->metrics.horiAdvance += xstr * 2; slot->metrics.vertBearingX -= xstr; slot->metrics.vertBearingY += ystr * 2; slot->metrics.vertAdvance += ystr * 2; /*center_dx = (int)( (double)xstr / 2 * (double)actual_face->face->size->metrics.x_scale / (80000) ); center_dy = (int)( (double)ystr / 2 * (double)actual_face->face->size->metrics.y_scale / (65536) );*/ center_dx = (int)( (double)rend->bold_strength * (double)actual_face->face->size->metrics.x_ppem / 80); center_dy = (int)( (double)rend->bold_strength * (double)actual_face->face->size->metrics.y_ppem / 80); #ifdef GLYPH_LOG if (glyph_log) fprintf(glyph_log," center_x += %.1f\n",((double)center_dx)/64); if (glyph_log) fprintf(glyph_log," center_y += %.1f\n",((double)center_dx)/64); #endif center_x += center_dx; center_y += center_dy; /*center_x += xstr;*/ /*center_y += ymin;*/ /*FT_GlyphSlot_Embolden(slot);*/ } } /* Getting a glyph from FreeType */ if (!error) { error = FT_Get_Glyph(actual_face->face->glyph, &ft_glyph); error = error || !ft_glyph; if (error) _gk_msg("Error: %s: Can't get a glyph with FT_Get_Glyph() call. Glyph (#%d) for character U+%04X\n", funcname,glyph_index,unicode); } /* Transforming the glyph to apply rotation and italics */ if (!error && ft_glyph->format==FT_GLYPH_FORMAT_OUTLINE && rend->do_matrix_transform) { error = FT_Glyph_Transform(ft_glyph,&rend->matrix,0); if (!error) { FT_Vector c; c.x = center_x; c.y = center_y; FT_Vector_Transform(&c,&rend->matrix); center_x = c.x; center_y = c.y; } } /* Converting glyph to bitmap */ if (!error && ft_glyph->format==FT_GLYPH_FORMAT_OUTLINE) { error = FT_Glyph_To_Bitmap(&ft_glyph,rend->render_mode,0,1); if (error) _gk_msg("Error: %s: FT_Glyph_To_Bitmap() bugs on character U+%04X\n",funcname,unicode); } /* Checking if we have bitmap now */ if (!error) { error = (ft_glyph->format!=FT_GLYPH_FORMAT_BITMAP); if (error) _gk_msg("Error: %s: Glyph is not FT_GLYPH_FORMAT_BITMAP after rendering with FT_Glyph_To_Bitmap()\n",funcname); } #ifdef GLYPH_LOG /* { if (glyph_log) { fprintf(glyph_log," We got a bitmap glyph from FreeType!\n"); if (ft_glyph->format==FT_GLYPH_FORMAT_BITMAP) { fprintf(glyph_log," Format: FT_GLYPH_FORMAT_BITMAP\n"); fprintf(glyph_log," Size: %dx%d, pitch: %d\n", ((FT_BitmapGlyph)ft_glyph)->bitmap.width, ((FT_BitmapGlyph)ft_glyph)->bitmap.rows, ((FT_BitmapGlyph)ft_glyph)->bitmap.pitch); if (((FT_BitmapGlyph)ft_glyph)->bitmap.pixel_mode==FT_PIXEL_MODE_MONO) { int x,y; int pitch = ((FT_BitmapGlyph)ft_glyph)->bitmap.pitch; fprintf(glyph_log," Pixel mode: FT_PIXEL_MODE_MONO\n"); fprintf(glyph_log," Buffer:\n"); for (y=0; y < ((FT_BitmapGlyph)ft_glyph)->bitmap.rows; y++) { fprintf(glyph_log," "); for (x=0; x < ((FT_BitmapGlyph)ft_glyph)->bitmap.width; x++) { unsigned char byte = ((unsigned char*)((FT_BitmapGlyph)ft_glyph)->bitmap.buffer)[y*pitch+x]; unsigned char mask = 128 >> (x%8); fprintf(glyph_log,"%s",(byte&mask)?" *":" ."); } fprintf(glyph_log,"\n"); } } else if (((FT_BitmapGlyph)ft_glyph)->bitmap.pixel_mode==FT_PIXEL_MODE_GRAY) fprintf(glyph_log," Pixel mode: FT_PIXEL_MODE_GRAY\n"); else if (((FT_BitmapGlyph)ft_glyph)->bitmap.pixel_mode==FT_PIXEL_MODE_GRAY2) fprintf(glyph_log," Pixel mode: FT_PIXEL_MODE_GRAY2\n"); else if (((FT_BitmapGlyph)ft_glyph)->bitmap.pixel_mode==FT_PIXEL_MODE_GRAY4) fprintf(glyph_log," Pixel mode: FT_PIXEL_MODE_GRAY4\n"); else if (((FT_BitmapGlyph)ft_glyph)->bitmap.pixel_mode==FT_PIXEL_MODE_LCD) fprintf(glyph_log," Pixel mode: FT_PIXEL_MODE_LCD\n"); else if (((FT_BitmapGlyph)ft_glyph)->bitmap.pixel_mode==FT_PIXEL_MODE_LCD_V) fprintf(glyph_log," Pixel mode: FT_PIXEL_MODE_LCD_V\n"); } else if (ft_glyph->format==FT_GLYPH_FORMAT_OUTLINE) { fprintf(glyph_log," Format: FT_GLYPH_FORMAT_OUTLINE\n"); } fprintf(glyph_log," Advance: ( %.1f , %.1f ) pixels\n", ((double)ft_glyph->advance.x)/0x10000,((double)ft_glyph->advance.y)/0x10000); } }*/ #endif if (!error) { error = ( ((FT_BitmapGlyph)ft_glyph)->bitmap.pitch < 0 ); if (error) _gk_msg("Error: rend_workout(): Rendered glyph has negative pitch value, can't handle\n"); /* FIXME */ } if (!error) { glyph = (GLYPH*)_gk_malloc(sizeof(GLYPH)); error = (glyph == 0); } if (error || !ft_glyph) { if (ft_glyph) FT_Done_Glyph(ft_glyph); if (unicode==rend->error_char) return 0; else return _gk_rend_render(rend,rend->error_char); } glyph->unicode = unicode; glyph->width = ((FT_BitmapGlyph)ft_glyph)->bitmap.width; glyph->height = ((FT_BitmapGlyph)ft_glyph)->bitmap.rows; glyph->left = ((FT_BitmapGlyph)ft_glyph)->left; glyph->top = ((FT_BitmapGlyph)ft_glyph)->top; glyph->advance_x = ft_glyph->advance.x >> 10; glyph->advance_y = ft_glyph->advance.y >> 10; glyph->center_x = (center_x + 31) / 64; glyph->center_y = (center_y + 31) / 64; glyph->index = 0; glyph->prev = 0; glyph->next = 0; glyph->bmp = 0; glyph->bmpsize = 0; _gk_msg("rendering character '%c'\n",unicode); bmp_size = glyph->width*glyph->height; if (!bmp_size) /* empty glyph, like space (' ') character */ { if (rend->index) _gk_glyph_index_add_glyph(rend->index,glyph); FT_Done_Glyph(ft_glyph); return glyph; } if (((FT_BitmapGlyph)ft_glyph)->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) { #ifdef GLYPH_TARGET_KNOWS_MONO_BITPACK int pitch1 = (glyph->width+7)>>3; int bitpack_size = glyph->height*pitch1; #ifdef GLYPH_TARGET_KNOWS_MONO_RLE7 int rle_size = 0; if (rend->index) rle_size = _gk_make_RLE7( ((FT_BitmapGlyph)ft_glyph)->bitmap.buffer, glyph->width, glyph->height, ((FT_BitmapGlyph)ft_glyph)->bitmap.pitch); if (rle_size>0 && rle_size<=bitpack_size) { glyph->bmp = (unsigned char*)_gk_malloc(rle_size); if (!glyph->bmp) { _gk_free(glyph); return 0; } memcpy(glyph->bmp,rle_buffer,rle_size); glyph->bmpsize = rle_size; } else #endif /* GLYPH_TARGET_KNOWS_MONO_RLE7 */ { glyph->bmp = (unsigned char*)_gk_malloc(bitpack_size+1); if (!glyph->bmp) { _gk_free(glyph); return 0; } glyph->bmp[0] = GLYPH_MONO_BITPACK; if ( ((FT_BitmapGlyph)ft_glyph)->bitmap.pitch == pitch1 ) memcpy( glyph->bmp+1, ((FT_BitmapGlyph)ft_glyph)->bitmap.buffer, bitpack_size ); else { unsigned char *d = glyph->bmp+1; int y = 0; for (; y<glyph->height; y++,d+=pitch1) memcpy( d, ((FT_BitmapGlyph)ft_glyph)->bitmap.buffer + y * ((FT_BitmapGlyph)ft_glyph)->bitmap.pitch, pitch1 ); } glyph->bmpsize = bitpack_size+1; } #else /* GLYPH_TARGET_KNOWS_MONO_BITPACK */ { int y = 0; unsigned char* b; glyph->bmp = (unsigned char*)_gk_malloc(bmp_size+1); if (!glyph->bmp) { _gk_free(glyph); return 0; } glyph->bmp[0] = GLYPH_UNCOMPRESSED; glyph->bmpsize = bmp_size+1; b = glyph->bmp + 1; for (; y<glyph->height; y++) { int x = 0; unsigned char* a = ((FT_BitmapGlyph)ft_glyph)->bitmap.buffer + y * ((FT_BitmapGlyph)ft_glyph)->bitmap.pitch; while (x<glyph->width) { if (x < glyph->width) { *b++ = *a&0x80 ? 255 : 0; x++; } if (x < glyph->width) { *b++ = *a&0x40 ? 255 : 0; x++; } if (x < glyph->width) { *b++ = *a&0x20 ? 255 : 0; x++; } if (x < glyph->width) { *b++ = *a&0x10 ? 255 : 0; x++; } if (x < glyph->width) { *b++ = *a&0x08 ? 255 : 0; x++; } if (x < glyph->width) { *b++ = *a&0x04 ? 255 : 0; x++; } if (x < glyph->width) { *b++ = *a&0x02 ? 255 : 0; x++; } if (x < glyph->width) { *b++ = *a&0x01 ? 255 : 0; x++; } a++; } } } #endif /* GLYPH_TARGET_KNOWS_MONO_BITPACK */ }
/** * Load glyphs corresponding to the UTF-32 codepoint code. */ static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code) { DrawTextContext *s = ctx->priv; FT_BitmapGlyph bitmapglyph; Glyph *glyph; struct AVTreeNode *node = NULL; int ret; /* load glyph into s->face->glyph */ if (FT_Load_Char(s->face, code, s->ft_load_flags)) return AVERROR(EINVAL); glyph = av_mallocz(sizeof(*glyph)); if (!glyph) { ret = AVERROR(ENOMEM); goto error; } glyph->code = code; if (FT_Get_Glyph(s->face->glyph, &glyph->glyph)) { ret = AVERROR(EINVAL); goto error; } if (s->borderw) { glyph->border_glyph = glyph->glyph; if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0) || FT_Glyph_To_Bitmap(&glyph->border_glyph, FT_RENDER_MODE_NORMAL, 0, 1)) { ret = AVERROR_EXTERNAL; goto error; } bitmapglyph = (FT_BitmapGlyph) glyph->border_glyph; glyph->border_bitmap = bitmapglyph->bitmap; } if (FT_Glyph_To_Bitmap(&glyph->glyph, FT_RENDER_MODE_NORMAL, 0, 1)) { ret = AVERROR_EXTERNAL; goto error; } bitmapglyph = (FT_BitmapGlyph) glyph->glyph; glyph->bitmap = bitmapglyph->bitmap; glyph->bitmap_left = bitmapglyph->left; glyph->bitmap_top = bitmapglyph->top; glyph->advance = s->face->glyph->advance.x >> 6; /* measure text height to calculate text_height (or the maximum text height) */ FT_Glyph_Get_CBox(glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox); /* cache the newly created glyph */ if (!(node = av_tree_node_alloc())) { ret = AVERROR(ENOMEM); goto error; } av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node); if (glyph_ptr) *glyph_ptr = glyph; return 0; error: if (glyph) av_freep(&glyph->glyph); av_freep(&glyph); av_freep(&node); return ret; }
void Font::makeDisplayList(FT_Face face, char ch) { // Load Glyph for character if (FT_Load_Glyph(face, FT_Get_Char_Index(face, ch), FT_LOAD_DEFAULT)) throw std::runtime_error("FT_Load_Glyph failed"); // Move Glyph into object FT_Glyph glyph; if (FT_Get_Glyph(face->glyph, &glyph)) throw std::runtime_error("FT_Get_Glyph failed"); // Convert Glyph to Bitmap FT_Glyph_To_Bitmap(&glyph, ft_render_mode_normal, 0, 1); FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph; FT_Bitmap &bitmap = bitmap_glyph->bitmap; // Resize to OpenGL power of 2 and two channels (luminosity and alpha) int width = nextPow2(bitmap.width); int height = nextPow2(bitmap.rows); GLubyte *expandedData = new GLubyte[2 * width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int pos = 2 * (x + y*width); expandedData[pos] = expandedData[pos+1] = (x >= bitmap.width || y >= bitmap.rows) ? 0 : bitmap.buffer[x + bitmap.width * y]; } } // Create OpenGL texture glBindTexture(GL_TEXTURE_2D, m_textures[ch]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expandedData); delete[] expandedData; // Now we create the Display List glNewList(m_displayLists+ch, GL_COMPILE); glBindTexture(GL_TEXTURE_2D, m_textures[ch]); glPushMatrix(); // Center character correctly glTranslatef(bitmap_glyph->left, 0, 0); glTranslatef(0, bitmap_glyph->top - bitmap.rows, 0); // Calculate real size versus padding space float x = float(bitmap.width) / float(width); float y = float(bitmap.rows) / float(height); // Draw the quad glBegin(GL_QUADS); glTexCoord2d(0, 0); glVertex2f(0, bitmap.rows); glTexCoord2d(0, y); glVertex2f(0, 0); glTexCoord2d(x, y); glVertex2f(bitmap.width, 0); glTexCoord2d(x, 0); glVertex2f(bitmap.width, bitmap.rows); glEnd(); glPopMatrix(); glTranslatef(face->glyph->advance.x >> 6, 0, 0); // Increment the raster position as if it were a bitmap font // glBitmap(0, 0, 0, 0, face->glyph->advance.x >> 6, 0, NULL); glEndList(); }
void agg_text_renderer<T>::render(glyph_positions const& pos) { glyphs_.clear(); prepare_glyphs(pos); FT_Error error; FT_Vector start; FT_Vector start_halo; int height = pixmap_.height(); pixel_position const& base_point = pos.get_base_point(); start.x = static_cast<FT_Pos>(base_point.x * (1 << 6)); start.y = static_cast<FT_Pos>((height - base_point.y) * (1 << 6)); start_halo = start; start.x += transform_.tx * 64; start.y += transform_.ty * 64; start_halo.x += halo_transform_.tx * 64; start_halo.y += halo_transform_.ty * 64; FT_Matrix halo_matrix; halo_matrix.xx = halo_transform_.sx * 0x10000L; halo_matrix.xy = halo_transform_.shx * 0x10000L; halo_matrix.yy = halo_transform_.sy * 0x10000L; halo_matrix.yx = halo_transform_.shy * 0x10000L; FT_Matrix matrix; matrix.xx = transform_.sx * 0x10000L; matrix.xy = transform_.shx * 0x10000L; matrix.yy = transform_.sy * 0x10000L; matrix.yx = transform_.shy * 0x10000L; // default formatting double halo_radius = 0; color black(0,0,0); unsigned fill = black.rgba(); unsigned halo_fill = black.rgba(); double text_opacity = 1.0; double halo_opacity = 1.0; for (auto const& glyph : glyphs_) { halo_fill = glyph.properties.halo_fill.rgba(); halo_opacity = glyph.properties.halo_opacity; halo_radius = glyph.properties.halo_radius * scale_factor_; // make sure we've got reasonable values. if (halo_radius <= 0.0 || halo_radius > 1024.0) continue; FT_Glyph g; error = FT_Glyph_Copy(glyph.image, &g); if (!error) { FT_Glyph_Transform(g, &halo_matrix, &start_halo); if (rasterizer_ == HALO_RASTERIZER_FULL) { stroker_->init(halo_radius); FT_Glyph_Stroke(&g, stroker_->get(), 1); error = FT_Glyph_To_Bitmap(&g, FT_RENDER_MODE_NORMAL, 0, 1); if (!error) { FT_BitmapGlyph bit = reinterpret_cast<FT_BitmapGlyph>(g); composite_bitmap(pixmap_, &bit->bitmap, halo_fill, bit->left, height - bit->top, halo_opacity, halo_comp_op_); } } else { error = FT_Glyph_To_Bitmap(&g, FT_RENDER_MODE_NORMAL, 0, 1); if (!error) { FT_BitmapGlyph bit = reinterpret_cast<FT_BitmapGlyph>(g); render_halo(&bit->bitmap, halo_fill, bit->left, height - bit->top, halo_radius, halo_opacity, halo_comp_op_); } } } FT_Done_Glyph(g); } // render actual text for (auto & glyph : glyphs_) { fill = glyph.properties.fill.rgba(); text_opacity = glyph.properties.text_opacity; FT_Glyph_Transform(glyph.image, &matrix, &start); error = FT_Glyph_To_Bitmap(&glyph.image ,FT_RENDER_MODE_NORMAL, 0, 1); if (!error) { FT_BitmapGlyph bit = reinterpret_cast<FT_BitmapGlyph>(glyph.image); composite_bitmap(pixmap_, &bit->bitmap, fill, bit->left, height - bit->top, text_opacity, comp_op_); } FT_Done_Glyph(glyph.image); } }
YUV_error text_to_overlay_player(p_info_rec* p_info, overlay* ovly, char* text, int max_width, int min_width, int x_margin, int y_margin, int center, int tab_width, int enable_align_right, char* font, const int size, const int aspect_ratio_num, const int aspect_ratio_den) { info_rec* info; BYTE* srcLine; BYTE* dstLine; int j; int error; int result; // initialise our data if (*p_info == NULL) { result = allocate_info(p_info); if (result < 0) return result; } info = *p_info; result = set_font(info, font, size, aspect_ratio_num, aspect_ratio_den); if (result < 0) return result; // render text using freetype2 { #define MAX_GLYPHS 100 FT_GlyphSlot slot = info->face->glyph; /* a small shortcut */ FT_UInt glyph_idx; FT_UInt last_glyph; FT_Vector delta; FT_Bool use_kerning; int pen_x, pen_y, n, margin; FT_Glyph glyphs[MAX_GLYPHS]; /* glyph image */ FT_Vector pos [MAX_GLYPHS]; /* glyph position */ FT_UInt num_glyphs; FT_UInt render_num_glyphs; FT_UInt vis_last_glyph; int vis_last; // index of end of last "word" int vis_width; // width to vis_last int x_offset = 0; int align_right = 0; int align_right_glyph = 0; int align_right_shift; use_kerning = FT_HAS_KERNING(info->face); // compute initial pen position using font metrics n = info->face->bbox.yMax - info->face->bbox.yMin;//info->face->ascender - info->face->descender; pen_x = ((-info->face->bbox.xMin * size) + (n / 2)) / n; pen_y = ((info->face->bbox.yMax * size) + (n / 2)) / n; margin = pen_x; // convert each character to a glyph and set its position num_glyphs = 0; vis_last = -1; vis_last_glyph = 0; vis_width = 0; last_glyph = FT_Get_Char_Index(info->face, ' '); for (n = 0; n < (int)strlen(text); n++) { if (text[n] == '\n') break; if (num_glyphs >= MAX_GLYPHS) break; if (tab_width > 0 && text[n] == '\t') { pen_x += size - (pen_x % size); } // a '>>' sequence results in alignment of the following text to the right else if (enable_align_right && !align_right && text[n] == '>' && text[n + 1] == '>') { n += 1; align_right = 1; align_right_glyph = num_glyphs; continue; } else { glyph_idx = FT_Get_Char_Index(info->face, text[n]); if (use_kerning && last_glyph && glyph_idx) { FT_Get_Kerning(info->face, last_glyph, glyph_idx, FT_KERNING_DEFAULT, &delta); pen_x += delta.x / 64; } error = FT_Load_Glyph(info->face, glyph_idx, FT_LOAD_DEFAULT); if (error) continue; /* ignore errors */ error = FT_Get_Glyph(info->face->glyph, &glyphs[num_glyphs]); if (error) continue; /* ignore errors */ if (pen_y - slot->bitmap_top < 0) { fprintf(stderr, "Character '%c' ascends too high\n", text[n]); pen_y = slot->bitmap_top; } if (pen_y - slot->bitmap_top + slot->bitmap.rows > size) { fprintf(stderr, "Character '%c' descends too low\n", text[n]); exit(1); } pos[num_glyphs].x = pen_x; pos[num_glyphs].y = pen_y; pen_x += slot->advance.x / 64; last_glyph = glyph_idx; num_glyphs++; } if (pen_x + (margin * 2) + (x_margin * 2) > max_width) break; if (text[n] != ' ' && (text[n+1] == ' ' || text[n+1] == '\0' || text[n+1] == '\n')) { vis_last_glyph = num_glyphs; vis_last = n; vis_width = pen_x; } } // truncate string to end of last word if (vis_last < 0) // haven't found end of first word! { vis_last_glyph = num_glyphs; vis_last = n - 1; vis_width = pen_x; } if (vis_width + (margin * 2) + (x_margin * 2) > max_width) { vis_last_glyph--; vis_last--; vis_width -= slot->advance.x / 64; } render_num_glyphs = vis_last_glyph; result = vis_last + 1; // do right alignment if there is space if (align_right) { align_right_shift = max_width - (vis_width + (margin * 2) + (x_margin * 2)); if (align_right_shift > 0) { for (n = align_right_glyph; n < (int)render_num_glyphs; n++) { pos[n].x += align_right_shift; } } } // find start of next word while (text[result] == ' ' || text[result] == '\n') result++; // set overlay dimensions ovly->w = vis_width + (margin * 2) + (x_margin * 2); // set width >= min_width and center if (ovly->w < min_width && min_width <= max_width) { if (center) { x_offset = (min_width - ovly->w) / 2; } ovly->w = min_width; } ovly->h = size + 2 * y_margin; // fprintf(stderr, "Area of '%s' = (%d x %d)\n", text, ovly->w, ovly->h); ovly->ssx = -1; ovly->ssy = -1; // alloc memory ovly->buff = malloc(ovly->w * ovly->h * 2); if (ovly->buff == NULL) return YUV_no_memory; memset(ovly->buff, 0, ovly->w * ovly->h * 2); ovly->Cbuff = NULL; // render glyphs for (n = 0; n < (int)render_num_glyphs; n++) { error = FT_Glyph_To_Bitmap(&glyphs[n], FT_RENDER_MODE_NORMAL, 0, 1); if (!error) { FT_BitmapGlyph bit = (FT_BitmapGlyph)glyphs[n]; srcLine = bit->bitmap.buffer; dstLine = ovly->buff + ((pos[n].y - bit->top) * ovly->w) + pos[n].x + bit->left + x_margin + y_margin * ovly->w + x_offset; // TODO: fix the problem with offsets if (dstLine < ovly->buff) dstLine = ovly->buff; for (j = 0; j < bit->bitmap.rows; j++) { memcpy(dstLine, srcLine, bit->bitmap.width); srcLine += bit->bitmap.width; dstLine += ovly->w; } } } // cleanup glyphs for (n = 0; n < (int)num_glyphs; n++) { FT_Done_Glyph(glyphs[n]); } } return result; // length of string actually rendered }
Text *text_create(Font *font, const char *char_string, int size) { const uint8_t *string = (const uint8_t *) char_string; Text *text; FT_Face face = font->face; FT_Glyph *glyph_string; FT_Vector *pos; FT_BBox bbox; FT_Long width, height; size_t len; float x, y; int i; if (FT_Set_Char_Size(face, 0, size*64, 0, 0) != 0) { log_err("Error setting character size\n"); return NULL; } text = ralloc(font, Text); if (text == NULL) { log_err("Out of memory\n"); return NULL; } text->size = size; text->vao = text->vbo = text->texture = 0; text->texture_image = NULL; text->string = (uint8_t *) ralloc_strdup(text, (const char *) string); len = strlen((const char *) string); /* Bytecount */ /* We allocate more space than necessary for the glyph string, better safe * than sorry. */ glyph_string = ralloc_array(text, FT_Glyph, len); pos = ralloc_array(text, FT_Vector, len); if (text->string == NULL || glyph_string == NULL || pos == NULL) { log_err("Out of memory\n"); ralloc_free(text); return NULL; } /* The UTF-8 bytestring is converted to an array of glyphs */ glyphstring_create(face, text, glyph_string, pos); /* We determine how big the text will be. This information is used * to compute the size of the texture we'll store the text in */ compute_glyphstring_bbox(glyph_string, pos, text->num_glyphs, &bbox); width = bbox.xMax - bbox.xMin; height = bbox.yMax - bbox.yMin; text->width = (width/64 + 0x3) & ~0x3; /* Align to 4 bytes */ text->height = height/64; text->texture_image = rzalloc_array(text, GLubyte, text->width * text->height); if (text->texture_image == NULL) { log_err("Out of memory\n"); for (i = 0; i < text->num_glyphs; i++) FT_Done_Glyph(glyph_string[i]); ralloc_free(text); return NULL; } /* Now we can render the text to a texture */ for (i = 0; i < text->num_glyphs; i++) { FT_Glyph glyph; FT_BitmapGlyph bitmap_glyph; FT_Vector pen; glyph = glyph_string[i]; pen.x = pos[i].x; pen.y = pos[i].y; /* Render the new glyph and destroy the old one */ if (FT_Glyph_To_Bitmap(&glyph, FT_LOAD_TARGET_NORMAL, &pen, 1) != 0) { log_err("Error rendering glyph to bitmap for character '%c'\n", string[i]); FT_Done_Glyph(glyph_string[i]); continue; } bitmap_glyph = (FT_BitmapGlyph) glyph; blit_glyph(bitmap_glyph, text->texture_image, (pen.x - bbox.xMin)/64, (pen.y - bbox.yMin)/64, text->width, text->height); FT_Done_Glyph(glyph); } ralloc_free(glyph_string); ralloc_free(pos); x = bbox.xMin/64; y = bbox.yMin/64; /* Why do we add text->width and not bbox.xMax? Because OpenGL wants * textures aligned at 4 bytes. This fixes a very subtle bug with * a very noticeable effect */ text->vertex[0].x = x; text->vertex[0].y = y; text->vertex[0].u = 0; text->vertex[0].v = 0; text->vertex[1].x = x + text->width; text->vertex[1].y = y; text->vertex[1].u = 1; text->vertex[1].v = 0; text->vertex[2].x = x + text->width; text->vertex[2].y = y + text->height; text->vertex[2].u = 1; text->vertex[2].v = 1; text->vertex[3].x = x; text->vertex[3].y = y + text->height; text->vertex[3].u = 0; text->vertex[3].v = 1; for (i = 0; i < 4; i++) { text->vertex[i].r = 0; text->vertex[i].g = 0; text->vertex[i].b = 1; text->vertex[i].a = 1; } return text; }
bool TGLFont::Load(const char* fontname) { char full_filename[512]; sprintf_s(full_filename,sizeof(full_filename),"Data/Fonts/%s", fontname); FT_Face ftFace; FT_Error err_code = FT_New_Face(ftLibrary,full_filename,0,&ftFace); if(err_code == FT_Err_Unknown_File_Format) { LogFile->Write("Bad font file format: "+string(fontname),LT_ERROR); return false; } else if (err_code) { LogFile->Write("Can't load font: "+string(fontname),LT_ERROR); return false; } if (iFontSize > min(ftFace->max_advance_width,ftFace->max_advance_height)) { FT_Done_Face(ftFace); LogFile->Write("Font size greater that supported font: "+string(fontname),LT_ERROR); return false; } if (FT_Set_Char_Size(ftFace, iFontSize*64, iFontSize*64, iHorizDPI, iVertDPI)) { FT_Done_Face(ftFace); LogFile->Write("Can't set font size for font: "+string(fontname),LT_ERROR); return false; } // new code FT_Long glyphs_count = ftFace->num_glyphs; if (glyphs_count == 0) { FT_Done_Face(ftFace); LogFile->Write("No glyphs in font: "+string(fontname),LT_ERROR); return false; } try { PLuint gridsize = GetGridSize(iFontSize); /*sprintf_s(full_filename,sizeof(full_filename),"???%s-%d", fontname, fontsize); pTex = pTextureSpool->CreateFontCashe(full_filename, gridsize*16, gridsize*16);*/ ((Texture::Texture2D&)pTex.GetObj()).LoadFromMem(0, gridsize*16, gridsize*16, Loader::Image::DT_RGBA); pGlyph = new Glyph2D*[MAXBYTE+1]; PLuint xoffset = 2 + iFontSize / 2 + 2; // reverse space for empty glyph PLuint yoffset = 2; PLint max_in_line = 0; for(PLuint i = 0; i <= MAXBYTE; i++) { wchar_t unicode_char = ctowc(i,iCodepage); if ((unicode_char != 0)&&(unicode_char < glyphs_count)) { FT_UInt ch_index = FT_Get_Char_Index(ftFace, unicode_char); if (ch_index) { if (FT_Load_Glyph( ftFace, ch_index, FT_LOAD_DEFAULT )) { pGlyph[i] = new Glyph2D(gridsize*16, 2, 2, iFontSize / 2, 1, 0); // empty glyph continue; } FT_Glyph ftGlyph; if (FT_Get_Glyph( ftFace->glyph, &ftGlyph )) { pGlyph[i] = new Glyph2D(gridsize*16, 2, 2, iFontSize / 2, 1, 0); // empty glyph continue; } if (FT_Glyph_To_Bitmap( &ftGlyph, FT_RENDER_MODE_NORMAL, 0, 1 )) { pGlyph[i] = new Glyph2D(gridsize*16, 2, 2, iFontSize / 2, 1, 0); // empty glyph continue; } FT_BitmapGlyph ftBitmapGlyph = (FT_BitmapGlyph)ftGlyph; FT_Bitmap& bitmap = ftBitmapGlyph->bitmap; if ((bitmap.rows == 0) || (bitmap.width == 0)) { pGlyph[i] = new Glyph2D(gridsize*16, 2, 2, iFontSize / 2, 1, 0); // empty glyph continue; } GLubyte* pExpData = new GLubyte[4*bitmap.width*bitmap.rows]; for (PLint k = 0; k < bitmap.rows; k++) { for(PLint j = 0; j < bitmap.width; j++) { unsigned char buf = bitmap.buffer[j + bitmap.width*k]; pExpData[4*(j+k*bitmap.width)] = 255; pExpData[4*(j+k*bitmap.width)+1] = 255; pExpData[4*(j+k*bitmap.width)+2] = 255; pExpData[4*(j+k*bitmap.width)+3] = buf; } } if (xoffset + bitmap.width >= gridsize*16) { xoffset = 2; yoffset += max_in_line + 2; } if (bitmap.rows > max_in_line) max_in_line = bitmap.rows; ((Texture::Texture2D&)pTex.GetObj()).SetRectFromMem(xoffset,yoffset,pExpData,bitmap.width,bitmap.rows,Loader::Image::DT_RGBA); pGlyph[i] = new Glyph2D(gridsize*16, xoffset, yoffset, bitmap.width, bitmap.rows, ftBitmapGlyph->top-bitmap.rows); delete[] pExpData; xoffset += bitmap.width + 2; } else pGlyph[i] = new Glyph2D(gridsize*16, 2, 2, iFontSize / 2, 1, 0); // empty glyph } else pGlyph[i] = new Glyph2D(gridsize*16, 2, 2, iFontSize / 2, 1, 0); // empty glyph } pTex->SendGPU(false); } catch(...) { delete[] pGlyph; return false; } FT_Done_Face(ftFace); sFontname = fontname; return true; }
void RenderText::draw(){ //glClearColor(1, 1, 1, 0); glEnable(GL_BLEND); //glEnable(GL_TEXTURE_2D); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glDisable(GL_DEPTH_TEST); //glDisable(GL_CULL_FACE); //glDisable(GL_TEXTURE_2D); //glDisable(GL_LIGHTING); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); int stageWidth, stageHeight; glfwGetWindowSize(&stageWidth, &stageHeight); glOrtho(0.0f, stageWidth, 0.0f, stageHeight, 0.0f, 1.0f); glMatrixMode(GL_MODELVIEW); int i; if(selectedInputs.size()>0&&selectedInputs[0]!=this&&inputAllowed&&text==""){ dispText = "Click to type here"; }else { dispText=text; } if(selectedInputs.size()>0&&selectedInputs[0]==this&&inputAllowed){ static int curserOn = 0; static float prevSwitchTime=glfwGetTime(); if(glfwGetTime()-prevSwitchTime>0.3){ curserOn = !curserOn; prevSwitchTime=glfwGetTime(); } if(curserOn){ dispText.append("_"); } } const size_t length = dispText.length(); textures = (GLuint*)calloc(length, sizeof(GLuint)); glGenTextures(length, textures); glPushMatrix(); glTranslatef(x, y, 0); glPushMatrix(); for (i = 0; i < length; ++i) { FT_Load_Glyph(face, FT_Get_Char_Index(face, dispText.at(i)), FT_LOAD_DEFAULT); FT_Get_Glyph(face->glyph, &glyph); FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1); bitmap_glyph = (FT_BitmapGlyph)glyph; bitmap = bitmap_glyph->bitmap; int width = RenderText::npo2(bitmap.width); int height = RenderText::npo2(bitmap.rows); float x = (float)bitmap.width / (float)width; float y = (float)bitmap.rows / (float)height; glBindTexture(GL_TEXTURE_2D, textures[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, 0); glPixelStorei(GL_UNPACK_ALIGNMENT,1); // no alignment glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bitmap.width, bitmap.rows, GL_ALPHA, GL_UNSIGNED_BYTE, bitmap.buffer); glPushMatrix(); glTranslatef(0, bitmap_glyph->top - bitmap.rows, 0); glBindTexture(GL_TEXTURE_2D, textures[i]); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, bitmap.rows); glTexCoord2f(0, y); glVertex2f(0, 0); glTexCoord2f(x, y); glVertex2f(bitmap.width, 0); glTexCoord2f(x, 0); glVertex2f(bitmap.width, bitmap.rows); glEnd(); glPopMatrix(); glTranslatef(glyph->advance.x / 65536, 0, 0); FT_Done_Glyph(glyph); } glPopMatrix(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glDeleteTextures(length, textures); free(textures); }
// Load a character glyph Font::Glyph Font::LoadGlyph( char ch, unsigned int size ) { Glyph glyph; // Ensure we can even retrieve the glyph if ( !_fontFace || !SetCurrentSize( size ) ) { return glyph; } // Attempt to load the font's glyph for the given character if ( 0 != FT_Load_Char( _myFontFace, ch, FT_LOAD_TARGET_NORMAL | FT_LOAD_FORCE_AUTOHINT ) ) { return glyph; } // Get the glyph's description FT_Glyph ftGlyph; if ( 0 != FT_Get_Glyph( _myFontFace->glyph, &ftGlyph ) ) { return glyph; } // Rasterize the glyph FT_Glyph_To_Bitmap( &ftGlyph, FT_RENDER_MODE_NORMAL, 0, 1 ); FT_Bitmap& bitmap = reinterpret_cast<FT_BitmapGlyph>( ftGlyph )->bitmap; // Get the glyph's advance glyph.Advance = static_cast<float>( _myFontFace->glyph->metrics.horiAdvance ) * KerningScale; int width = bitmap.width; int height = bitmap.rows; if ( ( width > 0 ) && ( height > 0 ) ) { // Get the glyph's page GlyphPage& page = _pages[ size ]; // Leave a small padding around characters, so that filtering doesn't // pollute them with pixels from neighbors const unsigned int padding = 1; // Find a good position for the new glyph into the texture UintRect emptyArea = FindGlyphRect( page, width + 2 * padding, height + 2 * padding );; // Ensure the texture data is in the center of the texture rectangle emptyArea.X += padding; emptyArea.Y += padding; emptyArea.Width -= 2 * padding; emptyArea.Height -= 2 * padding; glyph.TextureBounds = emptyArea; // Set the glyph's bounding box glyph.Bounds.X = ( _myFontFace->glyph->metrics.horiBearingX ) * KerningScale; glyph.Bounds.Y = -( _myFontFace->glyph->metrics.horiBearingY ) * KerningScale; glyph.Bounds.Width = ( _myFontFace->glyph->metrics.width ) * KerningScale; glyph.Bounds.Height = ( _myFontFace->glyph->metrics.height ) * KerningScale; // Extract the glyph's pixels from the bitmap _pixelBuffer.resize( width * height * 4, 255 ); const unsigned char* pixels = bitmap.buffer; if ( bitmap.pixel_mode == FT_PIXEL_MODE_MONO ) { // Pixels are 1 bit monochrome values for ( int y = 0; y < height; ++y ) { for ( int x = 0; x < width; ++x ) { // The color channels remain white, just fill the alpha channel std::size_t index = ( x + y * width ) * 4 + 3; _pixelBuffer[ index ] = ( ( pixels[ x / 8 ] ) & ( 1 << ( 7 - ( x % 8 ) ) ) ) ? 255 : 0; } pixels += bitmap.pitch; } } else { // Pixels are 8 bits gray levels for ( int y = 0; y < height; ++y ) { for ( int x = 0; x < width; ++x ) { // The color channels remain white, just fill the alpha channel std::size_t index = ( x + y * width ) * 4 + 3; _pixelBuffer[ index ] = pixels[ x ]; } pixels += bitmap.pitch; } } // Write the pixels to the texture page.Texture->UpdateArea( emptyArea.X, emptyArea.Y, emptyArea.Width, emptyArea.Height, &_pixelBuffer[ 0 ] ); } // Cleanup FT_Done_Glyph( ftGlyph ); return glyph; }
void SubtitleRenderer::load_glyph(char32_t codepoint) { VGfloat escapement[2]{}; auto load_glyph_internal = [&](FT_Face ft_face, VGFont vg_font, bool border) { try { auto glyph_index = FT_Get_Char_Index(ft_face, codepoint); ENFORCE(!FT_Load_Glyph(ft_face, glyph_index, FT_LOAD_NO_HINTING)); FT_Glyph glyph; ENFORCE(!FT_Get_Glyph(ft_face->glyph, &glyph)); SCOPE_EXIT {FT_Done_Glyph(glyph);}; if (border) ENFORCE(!FT_Glyph_StrokeBorder(&glyph, ft_stroker_, 0, 1)); ENFORCE(!FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, NULL, 1)); FT_BitmapGlyph bit_glyph = (FT_BitmapGlyph) glyph; FT_Bitmap& bitmap = bit_glyph->bitmap; VGImage image{}; VGfloat glyph_origin[2]{}; if (bitmap.width > 0 && bitmap.rows > 0) { constexpr VGfloat blur_stddev = 0.6; const int padding = static_cast<int>(3*blur_stddev + 0.5); const int image_width = bitmap.width + padding*2; const int image_height = bitmap.rows + padding*2; image = vgCreateImage(VG_A_8, image_width, image_height, VG_IMAGE_QUALITY_NONANTIALIASED); assert(image); if (bitmap.pitch > 0) { vgImageSubData(image, bitmap.buffer + bitmap.pitch*(bitmap.rows-1), -bitmap.pitch, VG_A_8, padding, padding, bitmap.width, bitmap.rows); assert(!vgGetError()); } else { vgImageSubData(image, bitmap.buffer, bitmap.pitch, VG_A_8, padding, padding, bitmap.width, bitmap.rows); assert(!vgGetError()); } auto softened_image = vgCreateImage(VG_A_8, image_width, image_height, VG_IMAGE_QUALITY_NONANTIALIASED); assert(image); // Even out hard and soft edges vgGaussianBlur(softened_image, image, blur_stddev, blur_stddev, VG_TILE_FILL); assert(!vgGetError()); vgDestroyImage(image); assert(!vgGetError()); image = softened_image; glyph_origin[0] = static_cast<VGfloat>(padding - bit_glyph->left); glyph_origin[1] = static_cast<VGfloat>(padding + bitmap.rows - bit_glyph->top - 1); } escapement[0] = static_cast<VGfloat>((ft_face->glyph->advance.x + 32) / 64); escapement[1] = 0; vgSetGlyphToImage(vg_font, codepoint, image, glyph_origin, escapement); assert(!vgGetError()); if (image) { vgDestroyImage(image); assert(!vgGetError()); } } catch(...) { escapement[0] = 0; escapement[1] = 0; vgSetGlyphToImage(vg_font, codepoint, VG_INVALID_HANDLE, escapement, escapement); assert(!vgGetError()); } }; load_glyph_internal(ft_face_, vg_font_, false); glyphs_[codepoint].advance = escapement[0]; load_glyph_internal(ft_face_, vg_font_border_, true); }
int text_to_overlay(p_info_rec* p_info, overlay* ovly, char* text, int max_width, char* font, const int size, const int aspect_ratio_num, const int aspect_ratio_den) { info_rec* info; BYTE* srcLine; BYTE* dstLine; int j; int error; int result; // initialise our data if (*p_info == NULL) { result = allocate_info(p_info); if (result < 0) return result; } info = *p_info; result = set_font(info, font, size, aspect_ratio_num, aspect_ratio_den); if (result < 0) return result; // render text using freetype2 { #define MAX_GLYPHS 100 FT_GlyphSlot slot = info->face->glyph; /* a small shortcut */ FT_UInt glyph_idx; FT_UInt last_glyph; FT_Vector delta; FT_Bool use_kerning; int pen_x, pen_y, n, margin; FT_Glyph glyphs[MAX_GLYPHS]; /* glyph image */ FT_Vector pos [MAX_GLYPHS]; /* glyph position */ FT_UInt num_glyphs; int vis_last; // index of end of last "word" int vis_width; // width to vis_last use_kerning = FT_HAS_KERNING(info->face); // font metrics are unreliable, so use actual rendered characters // set left margin using a capital M character glyph_idx = FT_Get_Char_Index(info->face, 'M'); FT_Load_Glyph(info->face, glyph_idx, FT_LOAD_DEFAULT); FT_Get_Glyph(info->face->glyph, &glyphs[0]); pen_x = slot->metrics.horiBearingX; margin = pen_x; FT_Done_Glyph(glyphs[0]); // set baseline using a capital A character glyph_idx = FT_Get_Char_Index(info->face, 'A'); FT_Load_Glyph(info->face, glyph_idx, FT_LOAD_DEFAULT); FT_Get_Glyph(info->face->glyph, &glyphs[0]); pen_y = slot->metrics.horiBearingY; FT_Done_Glyph(glyphs[0]); // convert each character to a glyph and set its position num_glyphs = 0; vis_last = -1; vis_width = 0; last_glyph = FT_Get_Char_Index(info->face, ' '); for (n = 0; n < (int)strlen(text); n++) { if (text[n] == '\n') break; if (num_glyphs >= MAX_GLYPHS) break; glyph_idx = FT_Get_Char_Index(info->face, text[n]); if (use_kerning && last_glyph && glyph_idx) { FT_Get_Kerning(info->face, last_glyph, glyph_idx, FT_KERNING_DEFAULT, &delta); pen_x += delta.x; } error = FT_Load_Glyph(info->face, glyph_idx, FT_LOAD_DEFAULT); if (error) continue; /* ignore errors */ error = FT_Get_Glyph(info->face->glyph, &glyphs[num_glyphs]); if (error) continue; /* ignore errors */ if (pen_y - slot->metrics.horiBearingY < 0) { fprintf(stderr, "Character '%c' ascends too high\n", text[n]); pen_y = slot->metrics.horiBearingY; } if (pen_y - slot->metrics.horiBearingY + slot->metrics.height > size * 64) { fprintf(stderr, "Character '%c' descends too low\n", text[n]); exit(1); } pos[num_glyphs].x = pen_x; pos[num_glyphs].y = -pen_y; pen_x += slot->advance.x; last_glyph = glyph_idx; num_glyphs++; if (pen_x + (margin * 2) > max_width * 64) break; if (text[n] != ' ' && (text[n+1] == ' ' || text[n+1] == '\0' || text[n+1] == '\n')) { vis_last = n; vis_width = pen_x; } } // truncate string to end of last word if (vis_last < 0) // haven't found end of first word! { vis_last = num_glyphs - 1; vis_width = pen_x; } num_glyphs = vis_last + 1; // find start of next word result = num_glyphs; while (text[result] == ' ' || text[result] == '\n') result++; // set overlay dimensions ovly->w = (vis_width + (margin * 2)) / 64; ovly->h = size; // fprintf(stderr, "Area of '%s' = (%d x %d)\n", text, ovly->w, ovly->h); ovly->ssx = -1; ovly->ssy = -1; // alloc memory ovly->buff = malloc(ovly->w * ovly->h * 2); if (ovly->buff == NULL) return YUV_no_memory; memset(ovly->buff, 0, ovly->w * ovly->h * 2); ovly->Cbuff = NULL; // render glyphs in pre-calculated positions for (n = 0; n < (int)num_glyphs; n++) { error = FT_Glyph_To_Bitmap(&glyphs[n], FT_RENDER_MODE_NORMAL, &pos[n], 1); if (!error) { FT_BitmapGlyph bit = (FT_BitmapGlyph)glyphs[n]; srcLine = bit->bitmap.buffer; dstLine = ovly->buff - (bit->top * ovly->w) + bit->left; for (j = 0; j < bit->bitmap.rows; j++) { memcpy(dstLine, srcLine, bit->bitmap.width); srcLine += bit->bitmap.width; dstLine += ovly->w; } } FT_Done_Glyph(glyphs[n]); } } return result; // length of string actually rendered }