dynamic_font.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. /*************************************************************************/
  2. /* dynamic_font.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #ifdef FREETYPE_ENABLED
  31. #include "dynamic_font.h"
  32. #include "core/os/file_access.h"
  33. #include "core/os/os.h"
  34. #include FT_STROKER_H
  35. #define __STDC_LIMIT_MACROS
  36. #include <stdint.h>
  37. bool DynamicFontData::CacheID::operator<(CacheID right) const {
  38. return key < right.key;
  39. }
  40. Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(CacheID p_cache_id) {
  41. if (size_cache.has(p_cache_id)) {
  42. return Ref<DynamicFontAtSize>(size_cache[p_cache_id]);
  43. }
  44. Ref<DynamicFontAtSize> dfas;
  45. dfas.instance();
  46. dfas->font = Ref<DynamicFontData>(this);
  47. size_cache[p_cache_id] = dfas.ptr();
  48. dfas->id = p_cache_id;
  49. dfas->_load();
  50. return dfas;
  51. }
  52. void DynamicFontData::set_font_ptr(const uint8_t *p_font_mem, int p_font_mem_size) {
  53. font_mem = p_font_mem;
  54. font_mem_size = p_font_mem_size;
  55. }
  56. void DynamicFontData::set_font_path(const String &p_path) {
  57. font_path = p_path;
  58. }
  59. String DynamicFontData::get_font_path() const {
  60. return font_path;
  61. }
  62. void DynamicFontData::set_force_autohinter(bool p_force) {
  63. force_autohinter = p_force;
  64. }
  65. void DynamicFontData::_bind_methods() {
  66. ClassDB::bind_method(D_METHOD("set_antialiased", "antialiased"), &DynamicFontData::set_antialiased);
  67. ClassDB::bind_method(D_METHOD("is_antialiased"), &DynamicFontData::is_antialiased);
  68. ClassDB::bind_method(D_METHOD("set_font_path", "path"), &DynamicFontData::set_font_path);
  69. ClassDB::bind_method(D_METHOD("get_font_path"), &DynamicFontData::get_font_path);
  70. ClassDB::bind_method(D_METHOD("set_hinting", "mode"), &DynamicFontData::set_hinting);
  71. ClassDB::bind_method(D_METHOD("get_hinting"), &DynamicFontData::get_hinting);
  72. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "antialiased"), "set_antialiased", "is_antialiased");
  73. ADD_PROPERTY(PropertyInfo(Variant::INT, "hinting", PROPERTY_HINT_ENUM, "None,Light,Normal"), "set_hinting", "get_hinting");
  74. BIND_ENUM_CONSTANT(HINTING_NONE);
  75. BIND_ENUM_CONSTANT(HINTING_LIGHT);
  76. BIND_ENUM_CONSTANT(HINTING_NORMAL);
  77. ADD_PROPERTY(PropertyInfo(Variant::STRING, "font_path", PROPERTY_HINT_FILE, "*.ttf,*.otf"), "set_font_path", "get_font_path");
  78. }
  79. DynamicFontData::DynamicFontData() {
  80. antialiased = true;
  81. force_autohinter = false;
  82. hinting = DynamicFontData::HINTING_NORMAL;
  83. font_mem = NULL;
  84. font_mem_size = 0;
  85. }
  86. DynamicFontData::~DynamicFontData() {
  87. }
  88. ////////////////////
  89. HashMap<String, Vector<uint8_t> > DynamicFontAtSize::_fontdata;
  90. Error DynamicFontAtSize::_load() {
  91. int error = FT_Init_FreeType(&library);
  92. ERR_FAIL_COND_V_MSG(error != 0, ERR_CANT_CREATE, "Error initializing FreeType.");
  93. // FT_OPEN_STREAM is extremely slow only on Android.
  94. if (OS::get_singleton()->get_name() == "Android" && font->font_mem == NULL && font->font_path != String()) {
  95. // cache font only once for each font->font_path
  96. if (_fontdata.has(font->font_path)) {
  97. font->set_font_ptr(_fontdata[font->font_path].ptr(), _fontdata[font->font_path].size());
  98. } else {
  99. FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ);
  100. if (!f) {
  101. FT_Done_FreeType(library);
  102. ERR_FAIL_V_MSG(ERR_CANT_OPEN, "Cannot open font file '" + font->font_path + "'.");
  103. }
  104. size_t len = f->get_len();
  105. _fontdata[font->font_path] = Vector<uint8_t>();
  106. Vector<uint8_t> &fontdata = _fontdata[font->font_path];
  107. fontdata.resize(len);
  108. f->get_buffer(fontdata.ptrw(), len);
  109. font->set_font_ptr(fontdata.ptr(), len);
  110. f->close();
  111. }
  112. }
  113. if (font->font_mem == NULL && font->font_path != String()) {
  114. FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ);
  115. if (!f) {
  116. FT_Done_FreeType(library);
  117. ERR_FAIL_V_MSG(ERR_CANT_OPEN, "Cannot open font file '" + font->font_path + "'.");
  118. }
  119. memset(&stream, 0, sizeof(FT_StreamRec));
  120. stream.base = NULL;
  121. stream.size = f->get_len();
  122. stream.pos = 0;
  123. stream.descriptor.pointer = f;
  124. stream.read = _ft_stream_io;
  125. stream.close = _ft_stream_close;
  126. FT_Open_Args fargs;
  127. memset(&fargs, 0, sizeof(FT_Open_Args));
  128. fargs.flags = FT_OPEN_STREAM;
  129. fargs.stream = &stream;
  130. error = FT_Open_Face(library, &fargs, 0, &face);
  131. } else if (font->font_mem) {
  132. memset(&stream, 0, sizeof(FT_StreamRec));
  133. stream.base = (unsigned char *)font->font_mem;
  134. stream.size = font->font_mem_size;
  135. stream.pos = 0;
  136. FT_Open_Args fargs;
  137. memset(&fargs, 0, sizeof(FT_Open_Args));
  138. fargs.memory_base = (unsigned char *)font->font_mem;
  139. fargs.memory_size = font->font_mem_size;
  140. fargs.flags = FT_OPEN_MEMORY;
  141. fargs.stream = &stream;
  142. error = FT_Open_Face(library, &fargs, 0, &face);
  143. } else {
  144. FT_Done_FreeType(library);
  145. ERR_FAIL_V_MSG(ERR_UNCONFIGURED, "DynamicFont uninitialized.");
  146. }
  147. //error = FT_New_Face( library, src_path.utf8().get_data(),0,&face );
  148. if (error == FT_Err_Unknown_File_Format) {
  149. FT_Done_FreeType(library);
  150. ERR_FAIL_V_MSG(ERR_FILE_CANT_OPEN, "Unknown font format.");
  151. } else if (error) {
  152. FT_Done_FreeType(library);
  153. ERR_FAIL_V_MSG(ERR_FILE_CANT_OPEN, "Error loading font.");
  154. }
  155. if (FT_HAS_COLOR(face) && face->num_fixed_sizes > 0) {
  156. int best_match = 0;
  157. int diff = ABS(id.size - ((int64_t)face->available_sizes[0].width));
  158. scale_color_font = float(id.size * oversampling) / face->available_sizes[0].width;
  159. for (int i = 1; i < face->num_fixed_sizes; i++) {
  160. int ndiff = ABS(id.size - ((int64_t)face->available_sizes[i].width));
  161. if (ndiff < diff) {
  162. best_match = i;
  163. diff = ndiff;
  164. scale_color_font = float(id.size * oversampling) / face->available_sizes[i].width;
  165. }
  166. }
  167. FT_Select_Size(face, best_match);
  168. } else {
  169. FT_Set_Pixel_Sizes(face, 0, id.size * oversampling);
  170. }
  171. ascent = (face->size->metrics.ascender / 64.0) / oversampling * scale_color_font;
  172. descent = (-face->size->metrics.descender / 64.0) / oversampling * scale_color_font;
  173. linegap = 0;
  174. texture_flags = 0;
  175. if (id.mipmaps)
  176. texture_flags |= Texture::FLAG_MIPMAPS;
  177. if (id.filter)
  178. texture_flags |= Texture::FLAG_FILTER;
  179. valid = true;
  180. return OK;
  181. }
  182. float DynamicFontAtSize::font_oversampling = 1.0;
  183. float DynamicFontAtSize::get_height() const {
  184. return ascent + descent;
  185. }
  186. float DynamicFontAtSize::get_ascent() const {
  187. return ascent;
  188. }
  189. float DynamicFontAtSize::get_descent() const {
  190. return descent;
  191. }
  192. const Pair<const DynamicFontAtSize::Character *, DynamicFontAtSize *> DynamicFontAtSize::_find_char_with_font(CharType p_char, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const {
  193. const Character *chr = char_map.getptr(p_char);
  194. ERR_FAIL_COND_V(!chr, (Pair<const Character *, DynamicFontAtSize *>(NULL, NULL)));
  195. if (!chr->found) {
  196. //not found, try in fallbacks
  197. for (int i = 0; i < p_fallbacks.size(); i++) {
  198. DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr());
  199. if (!fb->valid)
  200. continue;
  201. fb->_update_char(p_char);
  202. const Character *fallback_chr = fb->char_map.getptr(p_char);
  203. ERR_CONTINUE(!fallback_chr);
  204. if (!fallback_chr->found)
  205. continue;
  206. return Pair<const Character *, DynamicFontAtSize *>(fallback_chr, fb);
  207. }
  208. //not found, try 0xFFFD to display 'not found'.
  209. const_cast<DynamicFontAtSize *>(this)->_update_char(0xFFFD);
  210. chr = char_map.getptr(0xFFFD);
  211. ERR_FAIL_COND_V(!chr, (Pair<const Character *, DynamicFontAtSize *>(NULL, NULL)));
  212. }
  213. return Pair<const Character *, DynamicFontAtSize *>(chr, const_cast<DynamicFontAtSize *>(this));
  214. }
  215. Size2 DynamicFontAtSize::get_char_size(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const {
  216. if (!valid)
  217. return Size2(1, 1);
  218. const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
  219. Pair<const Character *, DynamicFontAtSize *> char_pair_with_font = _find_char_with_font(p_char, p_fallbacks);
  220. const Character *ch = char_pair_with_font.first;
  221. ERR_FAIL_COND_V(!ch, Size2());
  222. Size2 ret(0, get_height());
  223. if (ch->found) {
  224. ret.x = ch->advance;
  225. }
  226. return ret;
  227. }
  228. void DynamicFontAtSize::set_texture_flags(uint32_t p_flags) {
  229. texture_flags = p_flags;
  230. for (int i = 0; i < textures.size(); i++) {
  231. Ref<ImageTexture> &tex = textures.write[i].texture;
  232. if (!tex.is_null())
  233. tex->set_flags(p_flags);
  234. }
  235. }
  236. float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks, bool p_advance_only, bool p_outline) const {
  237. if (!valid)
  238. return 0;
  239. const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
  240. Pair<const Character *, DynamicFontAtSize *> char_pair_with_font = _find_char_with_font(p_char, p_fallbacks);
  241. const Character *ch = char_pair_with_font.first;
  242. DynamicFontAtSize *font = char_pair_with_font.second;
  243. ERR_FAIL_COND_V(!ch, 0.0);
  244. float advance = 0.0;
  245. // use normal character size if there's no outline character
  246. if (p_outline && !ch->found) {
  247. FT_GlyphSlot slot = face->glyph;
  248. int error = FT_Load_Char(face, p_char, FT_HAS_COLOR(face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT);
  249. if (!error) {
  250. error = FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
  251. if (!error) {
  252. Character character = Character::not_found();
  253. character = const_cast<DynamicFontAtSize *>(this)->_bitmap_to_character(slot->bitmap, slot->bitmap_top, slot->bitmap_left, slot->advance.x / 64.0);
  254. advance = character.advance;
  255. }
  256. }
  257. }
  258. if (ch->found) {
  259. ERR_FAIL_COND_V(ch->texture_idx < -1 || ch->texture_idx >= font->textures.size(), 0);
  260. if (!p_advance_only && ch->texture_idx != -1) {
  261. Point2 cpos = p_pos;
  262. cpos.x += ch->h_align;
  263. cpos.y -= font->get_ascent();
  264. cpos.y += ch->v_align;
  265. Color modulate = p_modulate;
  266. if (FT_HAS_COLOR(face)) {
  267. modulate.r = modulate.g = modulate.b = 1.0;
  268. }
  269. RID texture = font->textures[ch->texture_idx].texture->get_rid();
  270. VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, ch->rect.size), texture, ch->rect_uv, modulate, false, RID(), false);
  271. }
  272. advance = ch->advance;
  273. }
  274. return advance;
  275. }
  276. unsigned long DynamicFontAtSize::_ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count) {
  277. FileAccess *f = (FileAccess *)stream->descriptor.pointer;
  278. if (f->get_position() != offset) {
  279. f->seek(offset);
  280. }
  281. if (count == 0)
  282. return 0;
  283. return f->get_buffer(buffer, count);
  284. }
  285. void DynamicFontAtSize::_ft_stream_close(FT_Stream stream) {
  286. FileAccess *f = (FileAccess *)stream->descriptor.pointer;
  287. f->close();
  288. memdelete(f);
  289. }
  290. DynamicFontAtSize::Character DynamicFontAtSize::Character::not_found() {
  291. Character ch;
  292. ch.texture_idx = -1;
  293. ch.advance = 0;
  294. ch.h_align = 0;
  295. ch.v_align = 0;
  296. ch.found = false;
  297. return ch;
  298. }
  299. DynamicFontAtSize::TexturePosition DynamicFontAtSize::_find_texture_pos_for_glyph(int p_color_size, Image::Format p_image_format, int p_width, int p_height) {
  300. TexturePosition ret;
  301. ret.index = -1;
  302. ret.x = 0;
  303. ret.y = 0;
  304. int mw = p_width;
  305. int mh = p_height;
  306. for (int i = 0; i < textures.size(); i++) {
  307. const CharTexture &ct = textures[i];
  308. if (ct.texture->get_format() != p_image_format)
  309. continue;
  310. if (mw > ct.texture_size || mh > ct.texture_size) //too big for this texture
  311. continue;
  312. ret.y = 0x7FFFFFFF;
  313. ret.x = 0;
  314. for (int j = 0; j < ct.texture_size - mw; j++) {
  315. int max_y = 0;
  316. for (int k = j; k < j + mw; k++) {
  317. int y = ct.offsets[k];
  318. if (y > max_y)
  319. max_y = y;
  320. }
  321. if (max_y < ret.y) {
  322. ret.y = max_y;
  323. ret.x = j;
  324. }
  325. }
  326. if (ret.y == 0x7FFFFFFF || ret.y + mh > ct.texture_size)
  327. continue; //fail, could not fit it here
  328. ret.index = i;
  329. break;
  330. }
  331. if (ret.index == -1) {
  332. //could not find texture to fit, create one
  333. ret.x = 0;
  334. ret.y = 0;
  335. int texsize = MAX(id.size * oversampling * 8, 256);
  336. if (mw > texsize)
  337. texsize = mw; //special case, adapt to it?
  338. if (mh > texsize)
  339. texsize = mh; //special case, adapt to it?
  340. texsize = next_power_of_2(texsize);
  341. texsize = MIN(texsize, 4096);
  342. CharTexture tex;
  343. tex.texture_size = texsize;
  344. tex.imgdata.resize(texsize * texsize * p_color_size); //grayscale alpha
  345. {
  346. //zero texture
  347. PoolVector<uint8_t>::Write w = tex.imgdata.write();
  348. ERR_FAIL_COND_V(texsize * texsize * p_color_size > tex.imgdata.size(), ret);
  349. for (int i = 0; i < texsize * texsize * p_color_size; i++) {
  350. w[i] = 0;
  351. }
  352. }
  353. tex.offsets.resize(texsize);
  354. for (int i = 0; i < texsize; i++) //zero offsets
  355. tex.offsets.write[i] = 0;
  356. textures.push_back(tex);
  357. ret.index = textures.size() - 1;
  358. }
  359. return ret;
  360. }
  361. DynamicFontAtSize::Character DynamicFontAtSize::_bitmap_to_character(FT_Bitmap bitmap, int yofs, int xofs, float advance) {
  362. int w = bitmap.width;
  363. int h = bitmap.rows;
  364. int mw = w + rect_margin * 2;
  365. int mh = h + rect_margin * 2;
  366. ERR_FAIL_COND_V(mw > 4096, Character::not_found());
  367. ERR_FAIL_COND_V(mh > 4096, Character::not_found());
  368. int color_size = bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 2;
  369. Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8;
  370. TexturePosition tex_pos = _find_texture_pos_for_glyph(color_size, require_format, mw, mh);
  371. ERR_FAIL_COND_V(tex_pos.index < 0, Character::not_found());
  372. //fit character in char texture
  373. CharTexture &tex = textures.write[tex_pos.index];
  374. {
  375. PoolVector<uint8_t>::Write wr = tex.imgdata.write();
  376. for (int i = 0; i < h; i++) {
  377. for (int j = 0; j < w; j++) {
  378. int ofs = ((i + tex_pos.y + rect_margin) * tex.texture_size + j + tex_pos.x + rect_margin) * color_size;
  379. ERR_FAIL_COND_V(ofs >= tex.imgdata.size(), Character::not_found());
  380. switch (bitmap.pixel_mode) {
  381. case FT_PIXEL_MODE_MONO: {
  382. int byte = i * bitmap.pitch + (j >> 3);
  383. int bit = 1 << (7 - (j % 8));
  384. wr[ofs + 0] = 255; //grayscale as 1
  385. wr[ofs + 1] = (bitmap.buffer[byte] & bit) ? 255 : 0;
  386. } break;
  387. case FT_PIXEL_MODE_GRAY:
  388. wr[ofs + 0] = 255; //grayscale as 1
  389. wr[ofs + 1] = bitmap.buffer[i * bitmap.pitch + j];
  390. break;
  391. case FT_PIXEL_MODE_BGRA: {
  392. int ofs_color = i * bitmap.pitch + (j << 2);
  393. wr[ofs + 2] = bitmap.buffer[ofs_color + 0];
  394. wr[ofs + 1] = bitmap.buffer[ofs_color + 1];
  395. wr[ofs + 0] = bitmap.buffer[ofs_color + 2];
  396. wr[ofs + 3] = bitmap.buffer[ofs_color + 3];
  397. } break;
  398. // TODO: FT_PIXEL_MODE_LCD
  399. default:
  400. ERR_FAIL_V_MSG(Character::not_found(), "Font uses unsupported pixel format: " + itos(bitmap.pixel_mode) + ".");
  401. break;
  402. }
  403. }
  404. }
  405. }
  406. //blit to image and texture
  407. {
  408. Ref<Image> img = memnew(Image(tex.texture_size, tex.texture_size, 0, require_format, tex.imgdata));
  409. if (tex.texture.is_null()) {
  410. tex.texture.instance();
  411. tex.texture->create_from_image(img, Texture::FLAG_VIDEO_SURFACE | texture_flags);
  412. } else {
  413. tex.texture->set_data(img); //update
  414. }
  415. }
  416. // update height array
  417. for (int k = tex_pos.x; k < tex_pos.x + mw; k++) {
  418. tex.offsets.write[k] = tex_pos.y + mh;
  419. }
  420. Character chr;
  421. chr.h_align = xofs * scale_color_font / oversampling;
  422. chr.v_align = ascent - (yofs * scale_color_font / oversampling); // + ascent - descent;
  423. chr.advance = advance * scale_color_font / oversampling;
  424. chr.texture_idx = tex_pos.index;
  425. chr.found = true;
  426. chr.rect_uv = Rect2(tex_pos.x + rect_margin, tex_pos.y + rect_margin, w, h);
  427. chr.rect = chr.rect_uv;
  428. chr.rect.position /= oversampling;
  429. chr.rect.size = chr.rect.size * scale_color_font / oversampling;
  430. return chr;
  431. }
  432. DynamicFontAtSize::Character DynamicFontAtSize::_make_outline_char(CharType p_char) {
  433. Character ret = Character::not_found();
  434. if (FT_Load_Char(face, p_char, FT_LOAD_NO_BITMAP | (font->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0)) != 0)
  435. return ret;
  436. FT_Stroker stroker;
  437. if (FT_Stroker_New(library, &stroker) != 0)
  438. return ret;
  439. FT_Stroker_Set(stroker, (int)(id.outline_size * oversampling * 64.0), FT_STROKER_LINECAP_BUTT, FT_STROKER_LINEJOIN_ROUND, 0);
  440. FT_Glyph glyph;
  441. FT_BitmapGlyph glyph_bitmap;
  442. if (FT_Get_Glyph(face->glyph, &glyph) != 0)
  443. goto cleanup_stroker;
  444. if (FT_Glyph_Stroke(&glyph, stroker, 1) != 0)
  445. goto cleanup_glyph;
  446. if (FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1) != 0)
  447. goto cleanup_glyph;
  448. glyph_bitmap = (FT_BitmapGlyph)glyph;
  449. ret = _bitmap_to_character(glyph_bitmap->bitmap, glyph_bitmap->top, glyph_bitmap->left, glyph->advance.x / 65536.0);
  450. cleanup_glyph:
  451. FT_Done_Glyph(glyph);
  452. cleanup_stroker:
  453. FT_Stroker_Done(stroker);
  454. return ret;
  455. }
  456. void DynamicFontAtSize::_update_char(CharType p_char) {
  457. if (char_map.has(p_char))
  458. return;
  459. _THREAD_SAFE_METHOD_
  460. Character character = Character::not_found();
  461. FT_GlyphSlot slot = face->glyph;
  462. if (FT_Get_Char_Index(face, p_char) == 0) {
  463. char_map[p_char] = character;
  464. return;
  465. }
  466. int ft_hinting;
  467. switch (font->hinting) {
  468. case DynamicFontData::HINTING_NONE:
  469. ft_hinting = FT_LOAD_NO_HINTING;
  470. break;
  471. case DynamicFontData::HINTING_LIGHT:
  472. ft_hinting = FT_LOAD_TARGET_LIGHT;
  473. break;
  474. default:
  475. ft_hinting = FT_LOAD_TARGET_NORMAL;
  476. break;
  477. }
  478. int error = FT_Load_Char(face, p_char, FT_HAS_COLOR(face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (font->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting);
  479. if (error) {
  480. char_map[p_char] = character;
  481. return;
  482. }
  483. if (id.outline_size > 0) {
  484. character = _make_outline_char(p_char);
  485. } else {
  486. error = FT_Render_Glyph(face->glyph, font->antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
  487. if (!error)
  488. character = _bitmap_to_character(slot->bitmap, slot->bitmap_top, slot->bitmap_left, slot->advance.x / 64.0);
  489. }
  490. char_map[p_char] = character;
  491. }
  492. void DynamicFontAtSize::update_oversampling() {
  493. if (oversampling == font_oversampling || !valid)
  494. return;
  495. FT_Done_FreeType(library);
  496. textures.clear();
  497. char_map.clear();
  498. oversampling = font_oversampling;
  499. valid = false;
  500. _load();
  501. }
  502. DynamicFontAtSize::DynamicFontAtSize() {
  503. valid = false;
  504. rect_margin = 1;
  505. ascent = 1;
  506. descent = 1;
  507. linegap = 1;
  508. texture_flags = 0;
  509. oversampling = font_oversampling;
  510. scale_color_font = 1;
  511. }
  512. DynamicFontAtSize::~DynamicFontAtSize() {
  513. if (valid) {
  514. FT_Done_FreeType(library);
  515. }
  516. font->size_cache.erase(id);
  517. font.unref();
  518. }
  519. /////////////////////////
  520. void DynamicFont::_reload_cache() {
  521. ERR_FAIL_COND(cache_id.size < 1);
  522. if (!data.is_valid()) {
  523. data_at_size.unref();
  524. outline_data_at_size.unref();
  525. fallbacks.resize(0);
  526. fallback_data_at_size.resize(0);
  527. fallback_outline_data_at_size.resize(0);
  528. return;
  529. }
  530. data_at_size = data->_get_dynamic_font_at_size(cache_id);
  531. if (outline_cache_id.outline_size > 0) {
  532. outline_data_at_size = data->_get_dynamic_font_at_size(outline_cache_id);
  533. fallback_outline_data_at_size.resize(fallback_data_at_size.size());
  534. } else {
  535. outline_data_at_size.unref();
  536. fallback_outline_data_at_size.resize(0);
  537. }
  538. for (int i = 0; i < fallbacks.size(); i++) {
  539. fallback_data_at_size.write[i] = fallbacks.write[i]->_get_dynamic_font_at_size(cache_id);
  540. if (outline_cache_id.outline_size > 0)
  541. fallback_outline_data_at_size.write[i] = fallbacks.write[i]->_get_dynamic_font_at_size(outline_cache_id);
  542. }
  543. emit_changed();
  544. _change_notify();
  545. }
  546. void DynamicFont::set_font_data(const Ref<DynamicFontData> &p_data) {
  547. data = p_data;
  548. _reload_cache();
  549. emit_changed();
  550. _change_notify();
  551. }
  552. Ref<DynamicFontData> DynamicFont::get_font_data() const {
  553. return data;
  554. }
  555. void DynamicFont::set_size(int p_size) {
  556. if (cache_id.size == p_size)
  557. return;
  558. cache_id.size = p_size;
  559. outline_cache_id.size = p_size;
  560. _reload_cache();
  561. }
  562. int DynamicFont::get_size() const {
  563. return cache_id.size;
  564. }
  565. void DynamicFont::set_outline_size(int p_size) {
  566. if (outline_cache_id.outline_size == p_size)
  567. return;
  568. ERR_FAIL_COND(p_size < 0 || p_size > UINT8_MAX);
  569. outline_cache_id.outline_size = p_size;
  570. _reload_cache();
  571. }
  572. int DynamicFont::get_outline_size() const {
  573. return outline_cache_id.outline_size;
  574. }
  575. void DynamicFont::set_outline_color(Color p_color) {
  576. if (p_color != outline_color) {
  577. outline_color = p_color;
  578. emit_changed();
  579. _change_notify();
  580. }
  581. }
  582. Color DynamicFont::get_outline_color() const {
  583. return outline_color;
  584. }
  585. bool DynamicFont::get_use_mipmaps() const {
  586. return cache_id.mipmaps;
  587. }
  588. void DynamicFont::set_use_mipmaps(bool p_enable) {
  589. if (cache_id.mipmaps == p_enable)
  590. return;
  591. cache_id.mipmaps = p_enable;
  592. outline_cache_id.mipmaps = p_enable;
  593. _reload_cache();
  594. }
  595. bool DynamicFont::get_use_filter() const {
  596. return cache_id.filter;
  597. }
  598. void DynamicFont::set_use_filter(bool p_enable) {
  599. if (cache_id.filter == p_enable)
  600. return;
  601. cache_id.filter = p_enable;
  602. outline_cache_id.filter = p_enable;
  603. _reload_cache();
  604. }
  605. bool DynamicFontData::is_antialiased() const {
  606. return antialiased;
  607. }
  608. void DynamicFontData::set_antialiased(bool p_antialiased) {
  609. if (antialiased == p_antialiased)
  610. return;
  611. antialiased = p_antialiased;
  612. }
  613. DynamicFontData::Hinting DynamicFontData::get_hinting() const {
  614. return hinting;
  615. }
  616. void DynamicFontData::set_hinting(Hinting p_hinting) {
  617. if (hinting == p_hinting)
  618. return;
  619. hinting = p_hinting;
  620. }
  621. int DynamicFont::get_spacing(int p_type) const {
  622. if (p_type == SPACING_TOP) {
  623. return spacing_top;
  624. } else if (p_type == SPACING_BOTTOM) {
  625. return spacing_bottom;
  626. } else if (p_type == SPACING_CHAR) {
  627. return spacing_char;
  628. } else if (p_type == SPACING_SPACE) {
  629. return spacing_space;
  630. }
  631. return 0;
  632. }
  633. void DynamicFont::set_spacing(int p_type, int p_value) {
  634. if (p_type == SPACING_TOP) {
  635. spacing_top = p_value;
  636. } else if (p_type == SPACING_BOTTOM) {
  637. spacing_bottom = p_value;
  638. } else if (p_type == SPACING_CHAR) {
  639. spacing_char = p_value;
  640. } else if (p_type == SPACING_SPACE) {
  641. spacing_space = p_value;
  642. }
  643. emit_changed();
  644. _change_notify();
  645. }
  646. float DynamicFont::get_height() const {
  647. if (!data_at_size.is_valid())
  648. return 1;
  649. return data_at_size->get_height() + spacing_top + spacing_bottom;
  650. }
  651. float DynamicFont::get_ascent() const {
  652. if (!data_at_size.is_valid())
  653. return 1;
  654. return data_at_size->get_ascent() + spacing_top;
  655. }
  656. float DynamicFont::get_descent() const {
  657. if (!data_at_size.is_valid())
  658. return 1;
  659. return data_at_size->get_descent() + spacing_bottom;
  660. }
  661. Size2 DynamicFont::get_char_size(CharType p_char, CharType p_next) const {
  662. if (!data_at_size.is_valid())
  663. return Size2(1, 1);
  664. Size2 ret = data_at_size->get_char_size(p_char, p_next, fallback_data_at_size);
  665. if (p_char == ' ')
  666. ret.width += spacing_space + spacing_char;
  667. else if (p_next)
  668. ret.width += spacing_char;
  669. return ret;
  670. }
  671. bool DynamicFont::is_distance_field_hint() const {
  672. return false;
  673. }
  674. bool DynamicFont::has_outline() const {
  675. return outline_cache_id.outline_size > 0;
  676. }
  677. float DynamicFont::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate, bool p_outline) const {
  678. const Ref<DynamicFontAtSize> &font_at_size = p_outline && outline_cache_id.outline_size > 0 ? outline_data_at_size : data_at_size;
  679. if (!font_at_size.is_valid())
  680. return 0;
  681. const Vector<Ref<DynamicFontAtSize> > &fallbacks = p_outline && outline_cache_id.outline_size > 0 ? fallback_outline_data_at_size : fallback_data_at_size;
  682. Color color = p_outline && outline_cache_id.outline_size > 0 ? p_modulate * outline_color : p_modulate;
  683. // If requested outline draw, but no outline is present, simply return advance without drawing anything
  684. bool advance_only = p_outline && outline_cache_id.outline_size == 0;
  685. return font_at_size->draw_char(p_canvas_item, p_pos, p_char, p_next, color, fallbacks, advance_only, p_outline) + spacing_char;
  686. }
  687. void DynamicFont::set_fallback(int p_idx, const Ref<DynamicFontData> &p_data) {
  688. ERR_FAIL_COND(p_data.is_null());
  689. ERR_FAIL_INDEX(p_idx, fallbacks.size());
  690. fallbacks.write[p_idx] = p_data;
  691. fallback_data_at_size.write[p_idx] = fallbacks.write[p_idx]->_get_dynamic_font_at_size(cache_id);
  692. }
  693. void DynamicFont::add_fallback(const Ref<DynamicFontData> &p_data) {
  694. ERR_FAIL_COND(p_data.is_null());
  695. fallbacks.push_back(p_data);
  696. fallback_data_at_size.push_back(fallbacks.write[fallbacks.size() - 1]->_get_dynamic_font_at_size(cache_id)); //const..
  697. if (outline_cache_id.outline_size > 0)
  698. fallback_outline_data_at_size.push_back(fallbacks.write[fallbacks.size() - 1]->_get_dynamic_font_at_size(outline_cache_id));
  699. _change_notify();
  700. emit_changed();
  701. _change_notify();
  702. }
  703. int DynamicFont::get_fallback_count() const {
  704. return fallbacks.size();
  705. }
  706. Ref<DynamicFontData> DynamicFont::get_fallback(int p_idx) const {
  707. ERR_FAIL_INDEX_V(p_idx, fallbacks.size(), Ref<DynamicFontData>());
  708. return fallbacks[p_idx];
  709. }
  710. void DynamicFont::remove_fallback(int p_idx) {
  711. ERR_FAIL_INDEX(p_idx, fallbacks.size());
  712. fallbacks.remove(p_idx);
  713. fallback_data_at_size.remove(p_idx);
  714. emit_changed();
  715. _change_notify();
  716. }
  717. bool DynamicFont::_set(const StringName &p_name, const Variant &p_value) {
  718. String str = p_name;
  719. if (str.begins_with("fallback/")) {
  720. int idx = str.get_slicec('/', 1).to_int();
  721. Ref<DynamicFontData> fd = p_value;
  722. if (fd.is_valid()) {
  723. if (idx == fallbacks.size()) {
  724. add_fallback(fd);
  725. return true;
  726. } else if (idx >= 0 && idx < fallbacks.size()) {
  727. set_fallback(idx, fd);
  728. return true;
  729. } else {
  730. return false;
  731. }
  732. } else if (idx >= 0 && idx < fallbacks.size()) {
  733. remove_fallback(idx);
  734. return true;
  735. }
  736. }
  737. return false;
  738. }
  739. bool DynamicFont::_get(const StringName &p_name, Variant &r_ret) const {
  740. String str = p_name;
  741. if (str.begins_with("fallback/")) {
  742. int idx = str.get_slicec('/', 1).to_int();
  743. if (idx == fallbacks.size()) {
  744. r_ret = Ref<DynamicFontData>();
  745. return true;
  746. } else if (idx >= 0 && idx < fallbacks.size()) {
  747. r_ret = get_fallback(idx);
  748. return true;
  749. }
  750. }
  751. return false;
  752. }
  753. void DynamicFont::_get_property_list(List<PropertyInfo> *p_list) const {
  754. for (int i = 0; i < fallbacks.size(); i++) {
  755. p_list->push_back(PropertyInfo(Variant::OBJECT, "fallback/" + itos(i), PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"));
  756. }
  757. p_list->push_back(PropertyInfo(Variant::OBJECT, "fallback/" + itos(fallbacks.size()), PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"));
  758. }
  759. void DynamicFont::_bind_methods() {
  760. ClassDB::bind_method(D_METHOD("set_font_data", "data"), &DynamicFont::set_font_data);
  761. ClassDB::bind_method(D_METHOD("get_font_data"), &DynamicFont::get_font_data);
  762. ClassDB::bind_method(D_METHOD("set_size", "data"), &DynamicFont::set_size);
  763. ClassDB::bind_method(D_METHOD("get_size"), &DynamicFont::get_size);
  764. ClassDB::bind_method(D_METHOD("set_outline_size", "size"), &DynamicFont::set_outline_size);
  765. ClassDB::bind_method(D_METHOD("get_outline_size"), &DynamicFont::get_outline_size);
  766. ClassDB::bind_method(D_METHOD("set_outline_color", "color"), &DynamicFont::set_outline_color);
  767. ClassDB::bind_method(D_METHOD("get_outline_color"), &DynamicFont::get_outline_color);
  768. ClassDB::bind_method(D_METHOD("set_use_mipmaps", "enable"), &DynamicFont::set_use_mipmaps);
  769. ClassDB::bind_method(D_METHOD("get_use_mipmaps"), &DynamicFont::get_use_mipmaps);
  770. ClassDB::bind_method(D_METHOD("set_use_filter", "enable"), &DynamicFont::set_use_filter);
  771. ClassDB::bind_method(D_METHOD("get_use_filter"), &DynamicFont::get_use_filter);
  772. ClassDB::bind_method(D_METHOD("set_spacing", "type", "value"), &DynamicFont::set_spacing);
  773. ClassDB::bind_method(D_METHOD("get_spacing", "type"), &DynamicFont::get_spacing);
  774. ClassDB::bind_method(D_METHOD("add_fallback", "data"), &DynamicFont::add_fallback);
  775. ClassDB::bind_method(D_METHOD("set_fallback", "idx", "data"), &DynamicFont::set_fallback);
  776. ClassDB::bind_method(D_METHOD("get_fallback", "idx"), &DynamicFont::get_fallback);
  777. ClassDB::bind_method(D_METHOD("remove_fallback", "idx"), &DynamicFont::remove_fallback);
  778. ClassDB::bind_method(D_METHOD("get_fallback_count"), &DynamicFont::get_fallback_count);
  779. ADD_GROUP("Settings", "");
  780. ADD_PROPERTY(PropertyInfo(Variant::INT, "size", PROPERTY_HINT_RANGE, "1,1024,1"), "set_size", "get_size");
  781. ADD_PROPERTY(PropertyInfo(Variant::INT, "outline_size", PROPERTY_HINT_RANGE, "0,1024,1"), "set_outline_size", "get_outline_size");
  782. ADD_PROPERTY(PropertyInfo(Variant::COLOR, "outline_color"), "set_outline_color", "get_outline_color");
  783. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_mipmaps"), "set_use_mipmaps", "get_use_mipmaps");
  784. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_filter"), "set_use_filter", "get_use_filter");
  785. ADD_GROUP("Extra Spacing", "extra_spacing");
  786. ADD_PROPERTYI(PropertyInfo(Variant::INT, "extra_spacing_top"), "set_spacing", "get_spacing", SPACING_TOP);
  787. ADD_PROPERTYI(PropertyInfo(Variant::INT, "extra_spacing_bottom"), "set_spacing", "get_spacing", SPACING_BOTTOM);
  788. ADD_PROPERTYI(PropertyInfo(Variant::INT, "extra_spacing_char"), "set_spacing", "get_spacing", SPACING_CHAR);
  789. ADD_PROPERTYI(PropertyInfo(Variant::INT, "extra_spacing_space"), "set_spacing", "get_spacing", SPACING_SPACE);
  790. ADD_GROUP("Font", "");
  791. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "font_data", PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"), "set_font_data", "get_font_data");
  792. BIND_ENUM_CONSTANT(SPACING_TOP);
  793. BIND_ENUM_CONSTANT(SPACING_BOTTOM);
  794. BIND_ENUM_CONSTANT(SPACING_CHAR);
  795. BIND_ENUM_CONSTANT(SPACING_SPACE);
  796. }
  797. Mutex *DynamicFont::dynamic_font_mutex = NULL;
  798. SelfList<DynamicFont>::List *DynamicFont::dynamic_fonts = NULL;
  799. DynamicFont::DynamicFont() :
  800. font_list(this) {
  801. cache_id.size = 16;
  802. outline_cache_id.size = 16;
  803. spacing_top = 0;
  804. spacing_bottom = 0;
  805. spacing_char = 0;
  806. spacing_space = 0;
  807. outline_color = Color(1, 1, 1);
  808. if (dynamic_font_mutex) {
  809. dynamic_font_mutex->lock();
  810. dynamic_fonts->add(&font_list);
  811. dynamic_font_mutex->unlock();
  812. }
  813. }
  814. DynamicFont::~DynamicFont() {
  815. if (dynamic_font_mutex) {
  816. dynamic_font_mutex->lock();
  817. dynamic_fonts->remove(&font_list);
  818. dynamic_font_mutex->unlock();
  819. }
  820. }
  821. void DynamicFont::initialize_dynamic_fonts() {
  822. dynamic_fonts = memnew(SelfList<DynamicFont>::List());
  823. dynamic_font_mutex = Mutex::create();
  824. }
  825. void DynamicFont::finish_dynamic_fonts() {
  826. memdelete(dynamic_font_mutex);
  827. dynamic_font_mutex = NULL;
  828. memdelete(dynamic_fonts);
  829. dynamic_fonts = NULL;
  830. }
  831. void DynamicFont::update_oversampling() {
  832. Vector<Ref<DynamicFont> > changed;
  833. if (dynamic_font_mutex)
  834. dynamic_font_mutex->lock();
  835. SelfList<DynamicFont> *E = dynamic_fonts->first();
  836. while (E) {
  837. if (E->self()->data_at_size.is_valid()) {
  838. E->self()->data_at_size->update_oversampling();
  839. if (E->self()->outline_data_at_size.is_valid()) {
  840. E->self()->outline_data_at_size->update_oversampling();
  841. }
  842. for (int i = 0; i < E->self()->fallback_data_at_size.size(); i++) {
  843. if (E->self()->fallback_data_at_size[i].is_valid()) {
  844. E->self()->fallback_data_at_size.write[i]->update_oversampling();
  845. if (E->self()->has_outline() && E->self()->fallback_outline_data_at_size[i].is_valid()) {
  846. E->self()->fallback_outline_data_at_size.write[i]->update_oversampling();
  847. }
  848. }
  849. }
  850. changed.push_back(Ref<DynamicFont>(E->self()));
  851. }
  852. E = E->next();
  853. }
  854. if (dynamic_font_mutex)
  855. dynamic_font_mutex->unlock();
  856. for (int i = 0; i < changed.size(); i++) {
  857. changed.write[i]->emit_changed();
  858. }
  859. }
  860. /////////////////////////
  861. RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String &p_original_path, Error *r_error) {
  862. if (r_error)
  863. *r_error = ERR_FILE_CANT_OPEN;
  864. Ref<DynamicFontData> dfont;
  865. dfont.instance();
  866. dfont->set_font_path(p_path);
  867. if (r_error)
  868. *r_error = OK;
  869. return dfont;
  870. }
  871. void ResourceFormatLoaderDynamicFont::get_recognized_extensions(List<String> *p_extensions) const {
  872. p_extensions->push_back("ttf");
  873. p_extensions->push_back("otf");
  874. }
  875. bool ResourceFormatLoaderDynamicFont::handles_type(const String &p_type) const {
  876. return (p_type == "DynamicFontData");
  877. }
  878. String ResourceFormatLoaderDynamicFont::get_resource_type(const String &p_path) const {
  879. String el = p_path.get_extension().to_lower();
  880. if (el == "ttf" || el == "otf")
  881. return "DynamicFontData";
  882. return "";
  883. }
  884. #endif