Font.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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 char c) const
  66. {
  67. return glyphs_[glyphIndex_[c]];
  68. }
  69. short FontFace::GetKerning(unsigned char c, unsigned char d) const
  70. {
  71. if (!hasKerning_)
  72. return 0;
  73. if (c == '\n' || d == '\n')
  74. return 0;
  75. unsigned short leftIndex = glyphIndex_[c];
  76. unsigned short rightIndex = glyphIndex_[d];
  77. return glyphs_[leftIndex].kerning_[rightIndex];
  78. }
  79. OBJECTTYPESTATIC(FreeTypeLibrary);
  80. OBJECTTYPESTATIC(Font);
  81. Font::Font(Context* context) :
  82. Resource(context),
  83. fontDataSize_(0)
  84. {
  85. // Create & initialize FreeType library if it does not exist yet
  86. if (!GetSubsystem<FreeTypeLibrary>())
  87. context_->RegisterSubsystem(new FreeTypeLibrary(context_));
  88. }
  89. Font::~Font()
  90. {
  91. }
  92. void Font::RegisterObject(Context* context)
  93. {
  94. context->RegisterFactory<Font>();
  95. }
  96. bool Font::Load(Deserializer& source)
  97. {
  98. PROFILE(LoadFont);
  99. faces_.Clear();
  100. fontDataSize_ = source.GetSize();
  101. if (fontDataSize_)
  102. {
  103. fontData_ = new unsigned char[fontDataSize_];
  104. if (source.Read(&fontData_[0], fontDataSize_) != fontDataSize_)
  105. return false;
  106. }
  107. else
  108. {
  109. fontData_.Reset();
  110. return false;
  111. }
  112. SetMemoryUse(fontDataSize_);
  113. return true;
  114. }
  115. const FontFace* Font::GetFace(int pointSize)
  116. {
  117. Map<int, SharedPtr<FontFace> >::ConstIterator i = faces_.Find(pointSize);
  118. if (i != faces_.End())
  119. return i->second_;
  120. PROFILE(GetFontFace);
  121. FT_Face face;
  122. FT_Error error;
  123. FT_Library library = GetSubsystem<FreeTypeLibrary>()->getLibrary();
  124. if (pointSize <= 0)
  125. {
  126. LOGERROR("Zero or negative point size");
  127. return 0;
  128. }
  129. if (!fontDataSize_)
  130. {
  131. LOGERROR("Font not loaded");
  132. return 0;
  133. }
  134. error = FT_New_Memory_Face(library, &fontData_[0], fontDataSize_, 0, &face);
  135. if (error)
  136. {
  137. LOGERROR("Could not create font face");
  138. return 0;
  139. }
  140. error = FT_Set_Char_Size(face, 0, pointSize * 64, FONT_DPI, FONT_DPI);
  141. if (error)
  142. {
  143. FT_Done_Face(face);
  144. LOGERROR("Could not set font point size " + String(pointSize));
  145. return 0;
  146. }
  147. SharedPtr<FontFace> newFace(new FontFace());
  148. FT_GlyphSlot slot = face->glyph;
  149. unsigned freeIndex = 0;
  150. Map<unsigned, unsigned> toRemapped;
  151. PODVector<unsigned> toOriginal;
  152. // Build glyph mapping. Only render the glyphs needed by the charset
  153. for (unsigned i = 0; i < MAX_FONT_CHARS; ++i)
  154. {
  155. unsigned index = FT_Get_Char_Index(face, i);
  156. if (!toRemapped.Contains(index))
  157. {
  158. newFace->glyphIndex_[i] = freeIndex;
  159. toRemapped[index] = freeIndex;
  160. toOriginal.Push(index);
  161. ++freeIndex;
  162. }
  163. else
  164. newFace->glyphIndex_[i] = toRemapped[index];
  165. }
  166. // Load each of the glyphs to see the sizes & store other information
  167. int maxOffsetY = 0;
  168. int maxHeight = 0;
  169. for (unsigned i = 0; i < toOriginal.Size(); ++i)
  170. {
  171. FontGlyph newGlyph;
  172. error = FT_Load_Glyph(face, toOriginal[i], FT_LOAD_DEFAULT);
  173. if (!error)
  174. {
  175. // Note: position within texture will be filled later
  176. newGlyph.width_ = (short)((slot->metrics.width) >> 6);
  177. newGlyph.height_ = (short)((slot->metrics.height) >> 6);
  178. newGlyph.offsetX_ = (short)((slot->metrics.horiBearingX) >> 6);
  179. newGlyph.offsetY_ = (short)((face->size->metrics.ascender - slot->metrics.horiBearingY) >> 6);
  180. newGlyph.advanceX_ = (short)((slot->metrics.horiAdvance) >> 6);
  181. maxOffsetY = Max(maxOffsetY, newGlyph.offsetY_);
  182. maxHeight = Max(maxHeight, newGlyph.height_);
  183. }
  184. else
  185. {
  186. newGlyph.width_ = 0;
  187. newGlyph.height_ = 0;
  188. newGlyph.offsetX_ = 0;
  189. newGlyph.offsetY_ = 0;
  190. newGlyph.advanceX_ = 0;
  191. }
  192. newFace->glyphs_.Push(newGlyph);
  193. }
  194. // Store kerning if face has kerning information
  195. if (FT_HAS_KERNING(face))
  196. {
  197. newFace->hasKerning_ = true;
  198. unsigned numGlyphs = newFace->glyphs_.Size();
  199. for (unsigned i = 0; i < numGlyphs; ++i)
  200. {
  201. newFace->glyphs_[i].kerning_.Resize(numGlyphs);
  202. for (unsigned j = 0; j < numGlyphs; ++j)
  203. {
  204. unsigned leftIndex = toOriginal[i];
  205. unsigned rightIndex = toOriginal[j];
  206. FT_Vector vector;
  207. FT_Get_Kerning(face, leftIndex, rightIndex, FT_KERNING_DEFAULT, &vector);
  208. newFace->glyphs_[i].kerning_[j] = (short)(vector.x >> 6);
  209. }
  210. }
  211. }
  212. // Store point size and the height of a row. Use the height of the tallest font if taller than the specified row height
  213. newFace->pointSize_ = pointSize;
  214. newFace->rowHeight_ = Max((face->size->metrics.height + 63) >> 6, maxHeight);
  215. // Now try to pack into the smallest possible texture
  216. int texWidth = FONT_TEXTURE_MIN_SIZE;
  217. int texHeight = FONT_TEXTURE_MIN_SIZE;
  218. bool doubleHorizontal = true;
  219. for (;;)
  220. {
  221. bool success = true;
  222. // Check first for theoretical possible fit. If it fails, there is no need to try to fit
  223. int totalArea = 0;
  224. for (unsigned i = 0; i < newFace->glyphs_.Size(); ++i)
  225. totalArea += (newFace->glyphs_[i].width_ + 1) * (newFace->glyphs_[i].height_ + 1);
  226. if (totalArea > texWidth * texHeight)
  227. success = false;
  228. else
  229. {
  230. AreaAllocator allocator(texWidth, texHeight);
  231. for (unsigned i = 0; i < newFace->glyphs_.Size(); ++i)
  232. {
  233. if (newFace->glyphs_[i].width_ && newFace->glyphs_[i].height_)
  234. {
  235. int x, y;
  236. // Reserve an empty border between glyphs for filtering
  237. if (!allocator.Allocate(newFace->glyphs_[i].width_ + 1, newFace->glyphs_[i].height_ + 1, x, y))
  238. {
  239. success = false;
  240. break;
  241. }
  242. else
  243. {
  244. newFace->glyphs_[i].x_ = x;
  245. newFace->glyphs_[i].y_ = y;
  246. }
  247. }
  248. else
  249. {
  250. newFace->glyphs_[i].x_ = 0;
  251. newFace->glyphs_[i].y_ = 0;
  252. }
  253. }
  254. }
  255. if (!success)
  256. {
  257. // Alternate between doubling the horizontal and the vertical dimension
  258. if (doubleHorizontal)
  259. texWidth <<= 1;
  260. else
  261. texHeight <<= 1;
  262. if (texWidth > FONT_TEXTURE_MAX_SIZE || texHeight > FONT_TEXTURE_MAX_SIZE)
  263. {
  264. FT_Done_Face(face);
  265. LOGERROR("Font face could not be fit into the largest possible texture");
  266. return 0;
  267. }
  268. doubleHorizontal = !doubleHorizontal;
  269. }
  270. else
  271. break;
  272. }
  273. // Create the image for rendering the fonts
  274. SharedPtr<Image> image(new Image(context_));
  275. image->SetSize(texWidth, texHeight, 1);
  276. // First clear the whole image
  277. unsigned char* imageData = image->GetData();
  278. for (int y = 0; y < texHeight; ++y)
  279. {
  280. unsigned char* dest = imageData + texWidth * y;
  281. memset(dest, 0, texWidth);
  282. }
  283. // Render glyphs into texture, and find out a scaling value in case font uses less than full opacity (thin outlines)
  284. unsigned char avgMaxOpacity = 255;
  285. unsigned sumMaxOpacity = 0;
  286. unsigned samples = 0;
  287. for (unsigned i = 0; i < newFace->glyphs_.Size(); ++i)
  288. {
  289. FT_Load_Glyph(face, toOriginal[i], FT_LOAD_DEFAULT);
  290. FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
  291. unsigned char glyphOpacity = 0;
  292. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  293. {
  294. unsigned char* src = slot->bitmap.buffer + slot->bitmap.pitch * y;
  295. unsigned char* dest = imageData + texWidth * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  296. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  297. {
  298. dest[x] = src[x];
  299. glyphOpacity = Max(glyphOpacity, src[x]);
  300. }
  301. }
  302. if (glyphOpacity)
  303. {
  304. sumMaxOpacity += glyphOpacity;
  305. ++samples;
  306. }
  307. }
  308. // Clamp the minimum possible value to avoid overbrightening
  309. if (samples)
  310. avgMaxOpacity = Max(sumMaxOpacity / samples, 128);
  311. if (avgMaxOpacity < 255)
  312. {
  313. // Apply the scaling value if necessary
  314. float scale = 255.0f / avgMaxOpacity;
  315. for (unsigned i = 0; i < newFace->glyphs_.Size(); ++i)
  316. {
  317. for (int y = 0; y < newFace->glyphs_[i].height_; ++y)
  318. {
  319. unsigned char* dest = imageData + texWidth * (y + newFace->glyphs_[i].y_) + newFace->glyphs_[i].x_;
  320. for (int x = 0; x < newFace->glyphs_[i].width_; ++x)
  321. {
  322. int pixel = dest[x];
  323. dest[x] = Min((int)(pixel * scale), 255);
  324. }
  325. }
  326. }
  327. }
  328. FT_Done_Face(face);
  329. // Create the texture and load the image into it
  330. SharedPtr<Texture2D> texture(new Texture2D(context_));
  331. texture->SetNumLevels(1); // No mipmaps
  332. texture->SetAddressMode(COORD_U, ADDRESS_BORDER);
  333. texture->SetAddressMode(COORD_V, ADDRESS_BORDER),
  334. texture->SetBorderColor(Color(0.0f, 0.0f, 0.0f, 0.0f));
  335. if (!texture->SetSize(texWidth, texHeight, Graphics::GetAlphaFormat()) || !texture->Load(image, true))
  336. return 0;
  337. SetMemoryUse(GetMemoryUse() + texWidth * texHeight);
  338. newFace->texture_ = StaticCast<Texture>(texture);
  339. faces_[pointSize] = newFace;
  340. return newFace;
  341. }