Font.cpp 11 KB

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