dynamic_font.cpp 31 KB

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