dynamic_font_stb.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. /*************************************************************************/
  2. /* dynamic_font_stb.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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 "dynamic_font_stb.h"
  31. #ifndef FREETYPE_ENABLED
  32. #define STB_TRUETYPE_IMPLEMENTATION
  33. #include "core/os/file_access.h"
  34. void DynamicFontData::lock() {
  35. fr = font_data.read();
  36. if (fr.ptr() != last_data_ptr) {
  37. last_data_ptr = fr.ptr();
  38. if (!stbtt_InitFont(&info, last_data_ptr, 0)) {
  39. valid = false;
  40. } else {
  41. valid = true;
  42. }
  43. last_data_ptr = fr.ptr();
  44. }
  45. }
  46. void DynamicFontData::unlock() {
  47. fr = PoolVector<uint8_t>::Read();
  48. }
  49. void DynamicFontData::set_font_data(const PoolVector<uint8_t> &p_font) {
  50. //clear caches and stuff
  51. ERR_FAIL_COND(font_data.size());
  52. font_data = p_font;
  53. lock();
  54. if (valid) {
  55. stbtt_GetFontVMetrics(&info, &ascent, &descent, &linegap);
  56. descent = -descent + linegap;
  57. for (int i = 32; i < 1024; i++) {
  58. for (int j = 32; j < 1024; j++) {
  59. int kern = stbtt_GetCodepointKernAdvance(&info, i, j);
  60. if (kern != 0) {
  61. KerningPairKey kpk;
  62. kpk.A = i;
  63. kpk.B = j;
  64. kerning_map[kpk] = kern;
  65. }
  66. }
  67. }
  68. }
  69. unlock();
  70. //clear existing stuff
  71. ERR_FAIL_COND(!valid);
  72. }
  73. Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(int p_size) {
  74. ERR_FAIL_COND_V(!valid, Ref<DynamicFontAtSize>());
  75. if (size_cache.has(p_size)) {
  76. return Ref<DynamicFontAtSize>(size_cache[p_size]);
  77. }
  78. Ref<DynamicFontAtSize> dfas;
  79. dfas.instance();
  80. dfas->font = Ref<DynamicFontData>(this);
  81. size_cache[p_size] = dfas.ptr();
  82. dfas->size = p_size;
  83. lock();
  84. dfas->scale = stbtt_ScaleForPixelHeight(&info, p_size);
  85. unlock();
  86. return dfas;
  87. }
  88. DynamicFontData::DynamicFontData() {
  89. last_data_ptr = NULL;
  90. valid = false;
  91. }
  92. DynamicFontData::~DynamicFontData() {
  93. }
  94. ////////////////////
  95. float DynamicFontAtSize::get_height() const {
  96. return (font->ascent + font->descent) * scale;
  97. }
  98. float DynamicFontAtSize::get_ascent() const {
  99. return font->ascent * scale;
  100. }
  101. float DynamicFontAtSize::get_descent() const {
  102. return font->descent * scale;
  103. }
  104. Size2 DynamicFontAtSize::get_char_size(CharType p_char, CharType p_next) const {
  105. const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
  106. const Character *c = char_map.getptr(p_char);
  107. ERR_FAIL_COND_V(!c, Size2());
  108. Size2 ret(c->advance, get_height());
  109. if (p_next) {
  110. DynamicFontData::KerningPairKey kpk;
  111. kpk.A = p_char;
  112. kpk.B = p_next;
  113. const Map<DynamicFontData::KerningPairKey, int>::Element *K = font->kerning_map.find(kpk);
  114. if (K) {
  115. ret.x += K->get() * scale;
  116. }
  117. }
  118. return ret;
  119. }
  120. float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate, bool p_outline) const {
  121. const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
  122. const Character *c = char_map.getptr(p_char);
  123. if (!c) {
  124. return 0;
  125. }
  126. if (!p_outline) {
  127. Point2 cpos = p_pos;
  128. cpos.x += c->h_align;
  129. cpos.y -= get_ascent();
  130. cpos.y += c->v_align;
  131. ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), 0);
  132. if (c->texture_idx != -1)
  133. VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, c->rect.size), textures[c->texture_idx].texture->get_rid(), c->rect, p_modulate);
  134. }
  135. //textures[c->texture_idx].texture->draw(p_canvas_item,Vector2());
  136. float ret = c->advance;
  137. if (p_next) {
  138. DynamicFontData::KerningPairKey kpk;
  139. kpk.A = p_char;
  140. kpk.B = p_next;
  141. const Map<DynamicFontData::KerningPairKey, int>::Element *K = font->kerning_map.find(kpk);
  142. if (K) {
  143. ret += K->get() * scale;
  144. }
  145. }
  146. return ret;
  147. }
  148. void DynamicFontAtSize::_update_char(CharType p_char) {
  149. if (char_map.has(p_char))
  150. return;
  151. font->lock();
  152. int w, h, xofs, yofs;
  153. unsigned char *cpbitmap = stbtt_GetCodepointBitmap(&font->info, scale, scale, p_char, &w, &h, &xofs, &yofs);
  154. if (!cpbitmap) {
  155. //no glyph
  156. int advance;
  157. stbtt_GetCodepointHMetrics(&font->info, p_char, &advance, 0);
  158. Character ch;
  159. ch.texture_idx = -1;
  160. ch.advance = advance * scale;
  161. ch.h_align = 0;
  162. ch.v_align = 0;
  163. char_map[p_char] = ch;
  164. font->unlock();
  165. return;
  166. }
  167. int mw = w + rect_margin * 2;
  168. int mh = h + rect_margin * 2;
  169. if (mw > 4096 || mh > 4096) {
  170. stbtt_FreeBitmap(cpbitmap, NULL);
  171. font->unlock();
  172. ERR_FAIL_COND(mw > 4096);
  173. ERR_FAIL_COND(mh > 4096);
  174. }
  175. //find a texture to fit this...
  176. int tex_index = -1;
  177. int tex_x = 0;
  178. int tex_y = 0;
  179. for (int i = 0; i < textures.size(); i++) {
  180. CharTexture &ct = textures[i];
  181. if (mw > ct.texture_size || mh > ct.texture_size) //too big for this texture
  182. continue;
  183. tex_y = 0x7FFFFFFF;
  184. tex_x = 0;
  185. for (int j = 0; j < ct.texture_size - mw; j++) {
  186. int max_y = 0;
  187. for (int k = j; k < j + mw; k++) {
  188. int y = ct.offsets[k];
  189. if (y > max_y)
  190. max_y = y;
  191. }
  192. if (max_y < tex_y) {
  193. tex_y = max_y;
  194. tex_x = j;
  195. }
  196. }
  197. if (tex_y == 0x7FFFFFFF || tex_y + mh > ct.texture_size)
  198. continue; //fail, could not fit it here
  199. tex_index = i;
  200. break;
  201. }
  202. if (tex_index == -1) {
  203. //could not find texture to fit, create one
  204. tex_x = 0;
  205. tex_y = 0;
  206. int texsize = MAX(size * 8, 256);
  207. if (mw > texsize)
  208. texsize = mw; //special case, adapt to it?
  209. if (mh > texsize)
  210. texsize = mh; //special case, adapt to it?
  211. texsize = next_power_of_2(texsize);
  212. texsize = MIN(texsize, 4096);
  213. CharTexture tex;
  214. tex.texture_size = texsize;
  215. tex.imgdata.resize(texsize * texsize * 2); //grayscale alpha
  216. {
  217. //zero texture
  218. PoolVector<uint8_t>::Write w = tex.imgdata.write();
  219. ERR_FAIL_COND(texsize * texsize * 2 > tex.imgdata.size());
  220. for (int i = 0; i < texsize * texsize * 2; i++) {
  221. w[i] = 0;
  222. }
  223. }
  224. tex.offsets.resize(texsize);
  225. for (int i = 0; i < texsize; i++) //zero offsets
  226. tex.offsets[i] = 0;
  227. textures.push_back(tex);
  228. tex_index = textures.size() - 1;
  229. }
  230. //fit character in char texture
  231. CharTexture &tex = textures[tex_index];
  232. {
  233. PoolVector<uint8_t>::Write wr = tex.imgdata.write();
  234. for (int i = 0; i < h; i++) {
  235. for (int j = 0; j < w; j++) {
  236. int ofs = ((i + tex_y + rect_margin) * tex.texture_size + j + tex_x + rect_margin) * 2;
  237. ERR_FAIL_COND(ofs >= tex.imgdata.size());
  238. wr[ofs + 0] = 255; //grayscale as 1
  239. wr[ofs + 1] = cpbitmap[i * w + j]; //alpha as 0
  240. }
  241. }
  242. }
  243. //blit to image and texture
  244. {
  245. Ref<Image> img = memnew(Image(tex.texture_size, tex.texture_size, 0, Image::FORMAT_LA8, tex.imgdata));
  246. if (tex.texture.is_null()) {
  247. tex.texture.instance();
  248. tex.texture->create_from_image(img, Texture::FLAG_FILTER);
  249. } else {
  250. tex.texture->set_data(img); //update
  251. }
  252. }
  253. // update height array
  254. for (int k = tex_x; k < tex_x + mw; k++) {
  255. tex.offsets[k] = tex_y + mh;
  256. }
  257. int advance;
  258. stbtt_GetCodepointHMetrics(&font->info, p_char, &advance, 0);
  259. Character chr;
  260. chr.h_align = xofs;
  261. chr.v_align = yofs + get_ascent();
  262. chr.advance = advance * scale;
  263. chr.texture_idx = tex_index;
  264. chr.rect = Rect2(tex_x + rect_margin, tex_y + rect_margin, w, h);
  265. char_map[p_char] = chr;
  266. stbtt_FreeBitmap(cpbitmap, NULL);
  267. font->unlock();
  268. }
  269. DynamicFontAtSize::DynamicFontAtSize() {
  270. rect_margin = 1;
  271. }
  272. DynamicFontAtSize::~DynamicFontAtSize() {
  273. ERR_FAIL_COND(!font.ptr());
  274. font->size_cache.erase(size);
  275. }
  276. /////////////////////////
  277. void DynamicFont::_bind_methods() {
  278. ClassDB::bind_method(D_METHOD("set_font_data", "data"), &DynamicFont::set_font_data);
  279. ClassDB::bind_method(D_METHOD("get_font_data"), &DynamicFont::get_font_data);
  280. ClassDB::bind_method(D_METHOD("set_size", "data"), &DynamicFont::set_size);
  281. ClassDB::bind_method(D_METHOD("get_size"), &DynamicFont::get_size);
  282. ADD_PROPERTY(PropertyInfo(Variant::INT, "font/size"), "set_size", "get_size");
  283. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "font/font", PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"), "set_font_data", "get_font_data");
  284. }
  285. void DynamicFont::set_font_data(const Ref<DynamicFontData> &p_data) {
  286. data = p_data;
  287. data_at_size = data->_get_dynamic_font_at_size(size);
  288. }
  289. Ref<DynamicFontData> DynamicFont::get_font_data() const {
  290. return data;
  291. }
  292. void DynamicFont::set_size(int p_size) {
  293. if (size == p_size)
  294. return;
  295. size = p_size;
  296. ERR_FAIL_COND(p_size < 1);
  297. if (!data.is_valid())
  298. return;
  299. data_at_size = data->_get_dynamic_font_at_size(size);
  300. }
  301. int DynamicFont::get_size() const {
  302. return size;
  303. }
  304. float DynamicFont::get_height() const {
  305. if (!data_at_size.is_valid())
  306. return 1;
  307. return data_at_size->get_height();
  308. }
  309. float DynamicFont::get_ascent() const {
  310. if (!data_at_size.is_valid())
  311. return 1;
  312. return data_at_size->get_ascent();
  313. }
  314. float DynamicFont::get_descent() const {
  315. if (!data_at_size.is_valid())
  316. return 1;
  317. return data_at_size->get_descent();
  318. }
  319. Size2 DynamicFont::get_char_size(CharType p_char, CharType p_next) const {
  320. if (!data_at_size.is_valid())
  321. return Size2(1, 1);
  322. return data_at_size->get_char_size(p_char, p_next);
  323. }
  324. bool DynamicFont::is_distance_field_hint() const {
  325. return false;
  326. }
  327. 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 {
  328. if (!data_at_size.is_valid())
  329. return 0;
  330. return data_at_size->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate, p_outline);
  331. }
  332. DynamicFont::DynamicFont() {
  333. size = 16;
  334. }
  335. DynamicFont::~DynamicFont() {
  336. }
  337. /////////////////////////
  338. RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String &p_original_path, Error *r_error) {
  339. if (r_error)
  340. *r_error = ERR_FILE_CANT_OPEN;
  341. FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
  342. ERR_FAIL_COND_V(!f, RES());
  343. PoolVector<uint8_t> data;
  344. data.resize(f->get_len());
  345. ERR_FAIL_COND_V(data.size() == 0, RES());
  346. {
  347. PoolVector<uint8_t>::Write w = data.write();
  348. f->get_buffer(w.ptr(), data.size());
  349. }
  350. Ref<DynamicFontData> dfd;
  351. dfd.instance();
  352. dfd->set_font_data(data);
  353. if (r_error)
  354. *r_error = OK;
  355. return dfd;
  356. }
  357. void ResourceFormatLoaderDynamicFont::get_recognized_extensions(List<String> *p_extensions) const {
  358. p_extensions->push_back("ttf");
  359. }
  360. bool ResourceFormatLoaderDynamicFont::handles_type(const String &p_type) const {
  361. return (p_type == "DynamicFontData");
  362. }
  363. String ResourceFormatLoaderDynamicFont::get_resource_type(const String &p_path) const {
  364. String el = p_path.get_extension().to_lower();
  365. if (el == "ttf")
  366. return "DynamicFontData";
  367. return "";
  368. }
  369. #endif