Font.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "AreaAllocator.h"
  25. #include "Context.h"
  26. #include "Deserializer.h"
  27. #include "Font.h"
  28. #include "Graphics.h"
  29. #include "Log.h"
  30. #include "Profiler.h"
  31. #include "Texture2D.h"
  32. #include <ft2build.h>
  33. #include FT_FREETYPE_H
  34. #include "DebugNew.h"
  35. /// FreeType library subsystem.
  36. class FreeTypeLibrary : public Object
  37. {
  38. OBJECT(FreeTypeLibrary);
  39. public:
  40. /// Construct.
  41. FreeTypeLibrary(Context* context) :
  42. Object(context)
  43. {
  44. FT_Error error = FT_Init_FreeType(&mLibrary);
  45. if (error)
  46. LOGERROR("Could not initialize FreeType library");
  47. }
  48. /// Destruct.
  49. virtual ~FreeTypeLibrary()
  50. {
  51. FT_Done_FreeType(mLibrary);
  52. }
  53. FT_Library getLibrary() const { return mLibrary; }
  54. private:
  55. /// FreeType library.
  56. FT_Library mLibrary;
  57. };
  58. FontFace::FontFace() :
  59. hasKerning_(false)
  60. {
  61. }
  62. FontFace::~FontFace()
  63. {
  64. }
  65. const FontGlyph& FontFace::GetGlyph(unsigned c) const
  66. {
  67. HashMap<unsigned, unsigned>::ConstIterator i = glyphMapping_.Find(c);
  68. if (i != glyphMapping_.End())
  69. return glyphs_[i->second_];
  70. else
  71. return glyphs_[0];
  72. }
  73. short FontFace::GetKerning(unsigned c, unsigned d) const
  74. {
  75. if (!hasKerning_)
  76. return 0;
  77. if (c == '\n' || d == '\n')
  78. return 0;
  79. unsigned leftIndex = 0;
  80. unsigned rightIndex = 0;
  81. HashMap<unsigned, unsigned>::ConstIterator leftIt = glyphMapping_.Find(c);
  82. HashMap<unsigned, unsigned>::ConstIterator rightIt = glyphMapping_.Find(c);
  83. if (leftIt != glyphMapping_.End())
  84. leftIndex = leftIt->second_;
  85. if (rightIt != glyphMapping_.End())
  86. rightIndex = rightIt->second_;
  87. HashMap<unsigned, unsigned>::ConstIterator kerningIt = glyphs_[leftIndex].kerning_.Find(rightIndex);
  88. if (kerningIt != glyphs_[leftIndex].kerning_.End())
  89. return kerningIt->second_;
  90. else
  91. return 0;
  92. }
  93. OBJECTTYPESTATIC(FreeTypeLibrary);
  94. OBJECTTYPESTATIC(Font);
  95. Font::Font(Context* context) :
  96. Resource(context),
  97. fontDataSize_(0)
  98. {
  99. // Create & initialize FreeType library if it does not exist yet
  100. if (!GetSubsystem<FreeTypeLibrary>())
  101. context_->RegisterSubsystem(new FreeTypeLibrary(context_));
  102. }
  103. Font::~Font()
  104. {
  105. }
  106. void Font::RegisterObject(Context* context)
  107. {
  108. context->RegisterFactory<Font>();
  109. }
  110. bool Font::Load(Deserializer& source)
  111. {
  112. PROFILE(LoadFont);
  113. faces_.Clear();
  114. fontDataSize_ = source.GetSize();
  115. if (fontDataSize_)
  116. {
  117. fontData_ = new unsigned char[fontDataSize_];
  118. if (source.Read(&fontData_[0], fontDataSize_) != fontDataSize_)
  119. return false;
  120. }
  121. else
  122. {
  123. fontData_.Reset();
  124. return false;
  125. }
  126. SetMemoryUse(fontDataSize_);
  127. return true;
  128. }
  129. const FontFace* Font::GetFace(int pointSize)
  130. {
  131. HashMap<int, SharedPtr<FontFace> >::ConstIterator i = faces_.Find(pointSize);
  132. if (i != faces_.End())
  133. {
  134. if (!i->second_->texture_->IsDataLost())
  135. return i->second_;
  136. else
  137. {
  138. // Erase and reload face if texture data lost (OpenGL mode only)
  139. faces_.Erase(pointSize);
  140. }
  141. }
  142. PROFILE(GetFontFace);
  143. FT_Face face;
  144. FT_Error error;
  145. FT_Library library = GetSubsystem<FreeTypeLibrary>()->getLibrary();
  146. if (pointSize <= 0)
  147. {
  148. LOGERROR("Zero or negative point size");
  149. return 0;
  150. }
  151. if (!fontDataSize_)
  152. {
  153. LOGERROR("Font not loaded");
  154. return 0;
  155. }
  156. error = FT_New_Memory_Face(library, &fontData_[0], fontDataSize_, 0, &face);
  157. if (error)
  158. {
  159. LOGERROR("Could not create font face");
  160. return 0;
  161. }
  162. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  163. if (error)
  164. {
  165. FT_Done_Face(face);
  166. LOGERROR("Could not set font point size " + String(pointSize));
  167. return 0;
  168. }
  169. SharedPtr<FontFace> newFace(new FontFace());
  170. FT_GlyphSlot slot = face->glyph;
  171. unsigned numGlyphs = 0;
  172. // Build glyph mapping
  173. FT_UInt glyphIndex;
  174. FT_ULong charCode = FT_Get_First_Char(face, &glyphIndex);
  175. while (glyphIndex != 0)
  176. {
  177. numGlyphs = Max((int)glyphIndex + 1, (int)numGlyphs);
  178. newFace->glyphMapping_[charCode] = glyphIndex;
  179. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  180. }
  181. LOGDEBUG("Font face has " + String(numGlyphs) + " glyphs");
  182. // Load each of the glyphs to see the sizes & store other information
  183. int maxOffsetY = 0;
  184. int maxHeight = 0;
  185. for (unsigned i = 0; i < numGlyphs; ++i)
  186. {
  187. FontGlyph newGlyph;
  188. error = FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  189. if (!error)
  190. {
  191. // Note: position within texture will be filled later
  192. newGlyph.width_ = (short)((slot->metrics.width) >> 6);
  193. newGlyph.height_ = (short)((slot->metrics.height) >> 6);
  194. newGlyph.offsetX_ = (short)((slot->metrics.horiBearingX) >> 6);
  195. newGlyph.offsetY_ = (short)((face->size->metrics.ascender - slot->metrics.horiBearingY) >> 6);
  196. newGlyph.advanceX_ = (short)((slot->metrics.horiAdvance) >> 6);
  197. maxOffsetY = Max(maxOffsetY, newGlyph.offsetY_);
  198. maxHeight = Max(maxHeight, newGlyph.height_);
  199. }
  200. else
  201. {
  202. newGlyph.width_ = 0;
  203. newGlyph.height_ = 0;
  204. newGlyph.offsetX_ = 0;
  205. newGlyph.offsetY_ = 0;
  206. newGlyph.advanceX_ = 0;
  207. }
  208. newFace->glyphs_.Push(newGlyph);
  209. }
  210. // Store kerning if face has kerning information
  211. if (FT_HAS_KERNING(face))
  212. {
  213. newFace->hasKerning_ = true;
  214. unsigned numGlyphs = newFace->glyphs_.Size();
  215. for (unsigned i = 0; i < numGlyphs; ++i)
  216. {
  217. for (unsigned j = 0; j < numGlyphs; ++j)
  218. {
  219. FT_Vector vector;
  220. FT_Get_Kerning(face, i, j, FT_KERNING_DEFAULT, &vector);
  221. newFace->glyphs_[i].kerning_[j] = (short)(vector.x >> 6);
  222. }
  223. }
  224. }
  225. // Store point size and the height of a row. Use the height of the tallest font if taller than the specified row height
  226. newFace->pointSize_ = pointSize;
  227. newFace->rowHeight_ = Max((face->size->metrics.height + 63) >> 6, maxHeight);
  228. // Now try to pack into the smallest possible texture
  229. int texWidth = FONT_TEXTURE_MIN_SIZE;
  230. int texHeight = FONT_TEXTURE_MIN_SIZE;
  231. bool doubleHorizontal = true;
  232. for (;;)
  233. {
  234. bool success = true;
  235. // Check first for theoretical possible fit. If it fails, there is no need to try to fit
  236. int totalArea = 0;
  237. for (unsigned i = 0; i < newFace->glyphs_.Size(); ++i)
  238. totalArea += (newFace->glyphs_[i].width_ + 1) * (newFace->glyphs_[i].height_ + 1);
  239. if (totalArea > texWidth * texHeight)
  240. success = false;
  241. else
  242. {
  243. AreaAllocator allocator(texWidth, texHeight);
  244. for (unsigned i = 0; i < newFace->glyphs_.Size(); ++i)
  245. {
  246. if (newFace->glyphs_[i].width_ && newFace->glyphs_[i].height_)
  247. {
  248. int x, y;
  249. // Reserve an empty border between glyphs for filtering
  250. if (!allocator.Allocate(newFace->glyphs_[i].width_ + 1, newFace->glyphs_[i].height_ + 1, x, y))
  251. {
  252. success = false;
  253. break;
  254. }
  255. else
  256. {
  257. newFace->glyphs_[i].x_ = x;
  258. newFace->glyphs_[i].y_ = y;
  259. }
  260. }
  261. else
  262. {
  263. newFace->glyphs_[i].x_ = 0;
  264. newFace->glyphs_[i].y_ = 0;
  265. }
  266. }
  267. }
  268. if (!success)
  269. {
  270. // Alternate between doubling the horizontal and the vertical dimension
  271. if (doubleHorizontal)
  272. texWidth <<= 1;
  273. else
  274. texHeight <<= 1;
  275. if (texWidth > FONT_TEXTURE_MAX_SIZE || texHeight > FONT_TEXTURE_MAX_SIZE)
  276. {
  277. FT_Done_Face(face);
  278. LOGERROR("Font face could not be fit into the largest possible texture");
  279. return 0;
  280. }
  281. doubleHorizontal = !doubleHorizontal;
  282. }
  283. else
  284. break;
  285. }
  286. // Create the image for rendering the fonts
  287. SharedPtr<Image> image(new Image(context_));
  288. image->SetSize(texWidth, texHeight, 1);
  289. // First clear the whole image
  290. unsigned char* imageData = image->GetData();
  291. for (int y = 0; y < texHeight; ++y)
  292. {
  293. unsigned char* dest = imageData + texWidth * y;
  294. memset(dest, 0, texWidth);
  295. }
  296. // Render glyphs into texture, and find out a scaling value in case font uses less than full opacity (thin outlines)
  297. unsigned char avgMaxOpacity = 255;
  298. unsigned sumMaxOpacity = 0;
  299. unsigned samples = 0;
  300. for (unsigned i = 0; i < newFace->glyphs_.Size(); ++i)
  301. {
  302. if (!newFace->glyphs_[i].width_ || !newFace->glyphs_[i].height_)
  303. continue;
  304. FT_Load_Glyph(face, i, FT_LOAD_DEFAULT);
  305. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  306. unsigned char glyphOpacity = 0;
  307. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  308. {
  309. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  310. unsigned char* dest = imageData + texWidth * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  311. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  312. {
  313. dest[x] = src[x];
  314. glyphOpacity = Max(glyphOpacity, src[x]);
  315. }
  316. }
  317. if (glyphOpacity)
  318. {
  319. sumMaxOpacity += glyphOpacity;
  320. ++samples;
  321. }
  322. }
  323. // Clamp the minimum possible value to avoid overbrightening
  324. if (samples)
  325. avgMaxOpacity = Max(sumMaxOpacity / samples, 128);
  326. if (avgMaxOpacity < 255)
  327. {
  328. // Apply the scaling value if necessary
  329. float scale = 255.0f / avgMaxOpacity;
  330. for (unsigned i = 0; i < newFace->glyphs_.Size(); ++i)
  331. {
  332. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  333. {
  334. unsigned char* dest = imageData + texWidth * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  335. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  336. {
  337. int pixel = dest[x];
  338. dest[x] = Min((int)(pixel * scale), 255);
  339. }
  340. }
  341. }
  342. }
  343. FT_Done_Face(face);
  344. // Create the texture and load the image into it
  345. SharedPtr<Texture2D> texture(new Texture2D(context_));
  346. texture->SetNumLevels(1); // No mipmaps
  347. texture->SetAddressMode(COORD_U, ADDRESS_BORDER);
  348. texture->SetAddressMode(COORD_V, ADDRESS_BORDER),
  349. texture->SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  350. if (!texture->SetSize(texWidth, texHeight, Graphics::GetAlphaFormat()) || !texture->Load(image, true))
  351. return 0;
  352. SetMemoryUse(GetMemoryUse() + texWidth * texHeight);
  353. newFace->texture_ = StaticCast<Texture>(texture);
  354. faces_[pointSize] = newFace;
  355. return newFace;
  356. }