Font.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "AreaAllocator.h"
  24. #include "Context.h"
  25. #include "File.h"
  26. #include "Font.h"
  27. #include "Graphics.h"
  28. #include "Image.h"
  29. #include "Log.h"
  30. #include "Profiler.h"
  31. #include "Texture2D.h"
  32. #include "XMLFile.h"
  33. #include "ResourceCache.h"
  34. #include "FileSystem.h"
  35. #include "StringUtils.h"
  36. #include <ft2build.h>
  37. #include FT_FREETYPE_H
  38. #include "DebugNew.h"
  39. namespace Urho3D
  40. {
  41. /// FreeType library subsystem.
  42. class FreeTypeLibrary : public Object
  43. {
  44. OBJECT(FreeTypeLibrary);
  45. public:
  46. /// Construct.
  47. FreeTypeLibrary(Context* context) :
  48. Object(context)
  49. {
  50. FT_Error error = FT_Init_FreeType(&mLibrary);
  51. if (error)
  52. LOGERROR("Could not initialize FreeType library");
  53. }
  54. /// Destruct.
  55. virtual ~FreeTypeLibrary()
  56. {
  57. FT_Done_FreeType(mLibrary);
  58. }
  59. FT_Library getLibrary() const { return mLibrary; }
  60. private:
  61. /// FreeType library.
  62. FT_Library mLibrary;
  63. };
  64. FontFace::FontFace() :
  65. hasKerning_(false)
  66. {
  67. }
  68. FontFace::~FontFace()
  69. {
  70. }
  71. const FontGlyph& FontFace::GetGlyph(unsigned c) const
  72. {
  73. HashMap<unsigned, unsigned>::ConstIterator i = glyphMapping_.Find(c);
  74. if (i != glyphMapping_.End())
  75. return glyphs_[i->second_];
  76. else
  77. return glyphs_[0];
  78. }
  79. short FontFace::GetKerning(unsigned c, unsigned d) const
  80. {
  81. if (!hasKerning_)
  82. return 0;
  83. if (c == '\n' || d == '\n')
  84. return 0;
  85. unsigned leftIndex = 0;
  86. unsigned rightIndex = 0;
  87. HashMap<unsigned, unsigned>::ConstIterator leftIt = glyphMapping_.Find(c);
  88. HashMap<unsigned, unsigned>::ConstIterator rightIt = glyphMapping_.Find(d);
  89. if (leftIt != glyphMapping_.End())
  90. leftIndex = leftIt->second_;
  91. if (rightIt != glyphMapping_.End())
  92. rightIndex = rightIt->second_;
  93. HashMap<unsigned, unsigned>::ConstIterator kerningIt = glyphs_[leftIndex].kerning_.Find(rightIndex);
  94. if (kerningIt != glyphs_[leftIndex].kerning_.End())
  95. return kerningIt->second_;
  96. else
  97. return 0;
  98. }
  99. OBJECTTYPESTATIC(FreeTypeLibrary);
  100. OBJECTTYPESTATIC(Font);
  101. Font::Font(Context* context) :
  102. Resource(context),
  103. fontDataSize_(0),
  104. fontType_(FONT_TTF)
  105. {
  106. // Create & initialize FreeType library if it does not exist yet
  107. if (!GetSubsystem<FreeTypeLibrary>())
  108. context_->RegisterSubsystem(new FreeTypeLibrary(context_));
  109. }
  110. Font::~Font()
  111. {
  112. }
  113. void Font::RegisterObject(Context* context)
  114. {
  115. context->RegisterFactory<Font>();
  116. }
  117. bool Font::Load(Deserializer& source)
  118. {
  119. PROFILE(LoadFont);
  120. String ext = GetExtension(source.GetName()).ToLower();
  121. if (ext == ".xml" || ext == ".fnt")
  122. {
  123. fontType_ = FONT_IMAGE;
  124. return LoadImageFont(source);
  125. }
  126. else
  127. {
  128. fontType_ = FONT_TTF;
  129. return LoadTTFont(source);
  130. }
  131. }
  132. const FontFace* Font::GetFaceTTF(int pointSize)
  133. {
  134. HashMap<int, SharedPtr<FontFace> >::ConstIterator i = faces_.Find(pointSize);
  135. if (i != faces_.End())
  136. {
  137. if (!i->second_->texture_->IsDataLost())
  138. return i->second_;
  139. else
  140. {
  141. // Erase and reload face if texture data lost (OpenGL mode only)
  142. faces_.Erase(pointSize);
  143. }
  144. }
  145. PROFILE(GetFontFace);
  146. FT_Face face;
  147. FT_Error error;
  148. FT_Library library = GetSubsystem<FreeTypeLibrary>()->getLibrary();
  149. if (pointSize <= 0)
  150. {
  151. LOGERROR("Zero or negative point size");
  152. return 0;
  153. }
  154. if (!fontDataSize_)
  155. {
  156. LOGERROR("Font not loaded");
  157. return 0;
  158. }
  159. error = FT_New_Memory_Face(library, &fontData_[0], fontDataSize_, 0, &face);
  160. if (error)
  161. {
  162. LOGERROR("Could not create font face");
  163. return 0;
  164. }
  165. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  166. if (error)
  167. {
  168. FT_Done_Face(face);
  169. LOGERROR("Could not set font point size " + String(pointSize));
  170. return 0;
  171. }
  172. SharedPtr<FontFace> newFace(new FontFace());
  173. FT_GlyphSlot slot = face->glyph;
  174. unsigned numGlyphs = 0;
  175. // Build glyph mapping
  176. FT_UInt glyphIndex;
  177. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  178. while (glyphIndex != 0)
  179. {
  180. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  181. newFace->glyphMapping_[charCode] = glyphIndex;
  182. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  183. }
  184. LOGDEBUG("Font face has " + String(numGlyphs) + " glyphs");
  185. // Load each of the glyphs to see the sizes & store other information
  186. int maxOffsetY = 0;
  187. int maxHeight = 0;
  188. FT_Pos ascender = face->size->metrics.ascender;
  189. newFace->glyphs_.Reserve(numGlyphs);
  190. for (unsigned i = 0; i < numGlyphs; ++i)
  191. {
  192. FontGlyph newGlyph;
  193. error = FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  194. if (!error)
  195. {
  196. // Note: position within texture will be filled later
  197. newGlyph.width_ = (short)((slot->metrics.width) >> 6);
  198. newGlyph.height_ = (short)((slot->metrics.height) >> 6);
  199. newGlyph.offsetX_ = (short)((slot->metrics.horiBearingX) >> 6);
  200. newGlyph.offsetY_ = (short)((ascender - slot->metrics.horiBearingY) >> 6);
  201. newGlyph.advanceX_ = (short)((slot->metrics.horiAdvance) >> 6);
  202. maxOffsetY = Max(maxOffsetY, newGlyph.offsetY_);
  203. maxHeight = Max(maxHeight, newGlyph.height_);
  204. }
  205. else
  206. {
  207. newGlyph.width_ = 0;
  208. newGlyph.height_ = 0;
  209. newGlyph.offsetX_ = 0;
  210. newGlyph.offsetY_ = 0;
  211. newGlyph.advanceX_ = 0;
  212. }
  213. newFace->glyphs_.Push(newGlyph);
  214. }
  215. // Store kerning if face has kerning information
  216. if (FT_HAS_KERNING(face))
  217. {
  218. newFace->hasKerning_ = true;
  219. for (unsigned i = 0; i < numGlyphs; ++i)
  220. {
  221. for (unsigned j = 0; j < numGlyphs; ++j)
  222. {
  223. FT_Vector vector;
  224. FT_Get_Kerning(face, i, j, FT_KERNING_DEFAULT, &vector);
  225. newFace->glyphs_[i].kerning_[j] = (short)(vector.x >> 6);
  226. }
  227. }
  228. }
  229. // Store point size and the height of a row. Use the height of the tallest font if taller than the specified row height
  230. newFace->pointSize_ = pointSize;
  231. newFace->rowHeight_ = Max((face->size->metrics.height + 63) >> 6, maxHeight);
  232. // Now try to pack into the smallest possible texture
  233. int texWidth = FONT_TEXTURE_MIN_SIZE;
  234. int texHeight = FONT_TEXTURE_MIN_SIZE;
  235. bool doubleHorizontal = true;
  236. for (;;)
  237. {
  238. bool success = true;
  239. // Check first for theoretical possible fit. If it fails, there is no need to try to fit
  240. int totalArea = 0;
  241. for (unsigned i = 0; i < numGlyphs; ++i)
  242. totalArea += (newFace->glyphs_[i].width_ + 1) * (newFace->glyphs_[i].height_ + 1);
  243. if (totalArea > texWidth * texHeight)
  244. success = false;
  245. else
  246. {
  247. AreaAllocator allocator(texWidth, texHeight);
  248. for (unsigned i = 0; i < numGlyphs; ++i)
  249. {
  250. if (newFace->glyphs_[i].width_ && newFace->glyphs_[i].height_)
  251. {
  252. int x, y;
  253. // Reserve an empty border between glyphs for filtering
  254. if (!allocator.Allocate(newFace->glyphs_[i].width_ + 1, newFace->glyphs_[i].height_ + 1, x, y))
  255. {
  256. success = false;
  257. break;
  258. }
  259. else
  260. {
  261. newFace->glyphs_[i].x_ = x;
  262. newFace->glyphs_[i].y_ = y;
  263. }
  264. }
  265. else
  266. {
  267. newFace->glyphs_[i].x_ = 0;
  268. newFace->glyphs_[i].y_ = 0;
  269. }
  270. }
  271. }
  272. if (!success)
  273. {
  274. // Alternate between doubling the horizontal and the vertical dimension
  275. if (doubleHorizontal)
  276. texWidth <<= 1;
  277. else
  278. texHeight <<= 1;
  279. if (texWidth > FONT_TEXTURE_MAX_SIZE || texHeight > FONT_TEXTURE_MAX_SIZE)
  280. {
  281. FT_Done_Face(face);
  282. LOGERROR("Font face could not be fit into the largest possible texture");
  283. return 0;
  284. }
  285. doubleHorizontal = !doubleHorizontal;
  286. }
  287. else
  288. break;
  289. }
  290. // Create the image for rendering the fonts
  291. SharedPtr<Image> image(new Image(context_));
  292. image->SetSize(texWidth, texHeight, 1);
  293. // First clear the whole image
  294. unsigned char* imageData = image->GetData();
  295. for (int y = 0; y < texHeight; ++y)
  296. {
  297. unsigned char* dest = imageData + texWidth * y;
  298. memset(dest, 0, texWidth);
  299. }
  300. // Render glyphs into texture, and find out a scaling value in case font uses less than full opacity (thin outlines)
  301. unsigned char avgMaxOpacity = 255;
  302. unsigned sumMaxOpacity = 0;
  303. unsigned samples = 0;
  304. for (unsigned i = 0; i < numGlyphs; ++i)
  305. {
  306. if (!newFace->glyphs_[i].width_ || !newFace->glyphs_[i].height_)
  307. continue;
  308. FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  309. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  310. unsigned char glyphOpacity = 0;
  311. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  312. {
  313. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  314. unsigned char* dest = imageData + texWidth * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  315. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  316. {
  317. dest[x] = src[x];
  318. glyphOpacity = Max(glyphOpacity, src[x]);
  319. }
  320. }
  321. if (glyphOpacity)
  322. {
  323. sumMaxOpacity += glyphOpacity;
  324. ++samples;
  325. }
  326. }
  327. // Clamp the minimum possible value to avoid overbrightening
  328. if (samples)
  329. avgMaxOpacity = Max(sumMaxOpacity / samples, 128);
  330. if (avgMaxOpacity < 255)
  331. {
  332. // Apply the scaling value if necessary
  333. float scale = 255.0f / avgMaxOpacity;
  334. for (unsigned i = 0; i < numGlyphs; ++i)
  335. {
  336. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  337. {
  338. unsigned char* dest = imageData + texWidth * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  339. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  340. {
  341. int pixel = dest[x];
  342. dest[x] = Min((int)(pixel * scale), 255);
  343. }
  344. }
  345. }
  346. }
  347. FT_Done_Face(face);
  348. // Create the texture and load the image into it
  349. SharedPtr<Texture2D> texture(new Texture2D(context_));
  350. texture->SetNumLevels(1); // No mipmaps
  351. texture->SetAddressMode(COORD_U, ADDRESS_BORDER);
  352. texture->SetAddressMode(COORD_V, ADDRESS_BORDER),
  353. texture->SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  354. if (!texture->SetSize(texWidth, texHeight, Graphics::GetAlphaFormat()) || !texture->Load(image, true))
  355. return 0;
  356. SetMemoryUse(GetMemoryUse() + texWidth * texHeight);
  357. newFace->texture_ = texture;
  358. faces_[pointSize] = newFace;
  359. return newFace;
  360. }
  361. const FontFace* Font::GetFace( int pointSize )
  362. {
  363. switch(fontType_)
  364. {
  365. case FONT_TTF:
  366. return GetFaceTTF(pointSize);
  367. case FONT_IMAGE:
  368. return GetFaceImage(pointSize);
  369. default:
  370. return 0;
  371. }
  372. }
  373. bool Font::LoadTTFont( Deserializer& source )
  374. {
  375. faces_.Clear();
  376. fontDataSize_ = source.GetSize();
  377. if (fontDataSize_)
  378. {
  379. fontData_ = new unsigned char[fontDataSize_];
  380. if (source.Read(&fontData_[0], fontDataSize_) != fontDataSize_)
  381. return false;
  382. }
  383. else
  384. {
  385. fontData_.Reset();
  386. return false;
  387. }
  388. SetMemoryUse(fontDataSize_);
  389. return true;
  390. }
  391. bool Font::LoadImageFont(Deserializer& source)
  392. {
  393. SharedPtr<XMLFile> xmlReader(new XMLFile(context_));
  394. if (!xmlReader->Load(source))
  395. {
  396. LOGERROR("Can not load XML file");
  397. return false;
  398. }
  399. XMLElement root = xmlReader->GetRoot("font");
  400. if (root.IsNull())
  401. {
  402. LOGERROR("Can not find Font element");
  403. return false;
  404. }
  405. XMLElement pagesElem = root.GetChild("pages");
  406. if (pagesElem.IsNull())
  407. {
  408. LOGERROR("Can not find Pages element");
  409. return false;
  410. }
  411. /// \todo Support multiple pages
  412. XMLElement pageElem = pagesElem.GetChild("page");
  413. if (pageElem.IsNull())
  414. {
  415. LOGERROR("Can not find Page element");
  416. return false;
  417. }
  418. fontFace_ = new FontFace();
  419. XMLElement commonElem = root.GetChild("common");
  420. fontFace_->rowHeight_ = commonElem.GetInt("lineHeight");
  421. String textureFile = pageElem.GetAttribute("file");
  422. // Assume the font image is in the same directory as the XML description
  423. textureFile = GetPath(source.GetName()) + textureFile;
  424. ResourceCache* resourceCache = GetSubsystem<ResourceCache>();
  425. // Load texture manually to allow controlling the alpha channel mode
  426. SharedPtr<File> fontFile = resourceCache->GetFile(textureFile);
  427. SharedPtr<Image> fontImage(new Image(context_));
  428. if (!fontFile || !fontImage->Load(*fontFile))
  429. {
  430. LOGERROR("Failed to load font image file");
  431. return false;
  432. }
  433. fontFace_->texture_ = new Texture2D(context_);
  434. if (!fontFace_->texture_->Load(fontImage, true))
  435. {
  436. LOGERROR("Failed to create font texture");
  437. fontFace_->texture_.Reset();
  438. return false;
  439. }
  440. XMLElement charsElem = root.GetChild("chars");
  441. int count = charsElem.GetInt("count");
  442. fontFace_->glyphs_.Reserve(count);
  443. XMLElement charElem = charsElem.GetChild("char");
  444. while(!charElem.IsNull())
  445. {
  446. int id = charElem.GetInt("id");
  447. FontGlyph glyph;
  448. glyph.x_ = charElem.GetInt("x");
  449. glyph.y_ = charElem.GetInt("y");
  450. glyph.width_ = charElem.GetInt("width");
  451. glyph.height_ = charElem.GetInt("height");
  452. glyph.offsetX_ = charElem.GetInt("xoffset");
  453. glyph.offsetY_ = charElem.GetInt("yoffset");
  454. glyph.advanceX_ = charElem.GetInt("xadvance");
  455. unsigned index = fontFace_->glyphs_.Size();
  456. fontFace_->glyphs_.Push(glyph);
  457. fontFace_->glyphMapping_[id] = index;
  458. charElem = charElem.GetNext("char");
  459. }
  460. XMLElement kerningsElem = root.GetChild("kernings");
  461. if(kerningsElem.IsNull())
  462. {
  463. fontFace_->hasKerning_ = false;
  464. return true;
  465. }
  466. XMLElement kerningElem = kerningsElem.GetChild("kerning");
  467. while (!kerningElem.IsNull())
  468. {
  469. int first = kerningElem.GetInt("first");
  470. int second = kerningElem.GetInt("second");
  471. int amount = kerningElem.GetInt("amount");
  472. HashMap<unsigned, unsigned>::Iterator i = fontFace_->glyphMapping_.Find(first);
  473. if(i == fontFace_->glyphMapping_.End())
  474. continue;
  475. FontGlyph& fg = fontFace_->glyphs_[i->second_];
  476. fg.kerning_[second] = amount;
  477. kerningElem = kerningElem.GetNext("kerning");
  478. }
  479. SetMemoryUse(GetMemoryUse() + fontImage->GetWidth() * fontImage->GetHeight() * fontImage->GetComponents());
  480. return true;
  481. }
  482. const FontFace* Font::GetFaceImage(int pointSize)
  483. {
  484. return fontFace_;
  485. }
  486. }