resource_importer_imagefont.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /**************************************************************************/
  2. /* resource_importer_imagefont.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 "resource_importer_imagefont.h"
  31. #include "core/io/image_loader.h"
  32. #include "core/io/resource_saver.h"
  33. String ResourceImporterImageFont::get_importer_name() const {
  34. return "font_data_image";
  35. }
  36. String ResourceImporterImageFont::get_visible_name() const {
  37. return "Font Data (Monospace Image Font)";
  38. }
  39. void ResourceImporterImageFont::get_recognized_extensions(List<String> *p_extensions) const {
  40. if (p_extensions) {
  41. ImageLoader::get_recognized_extensions(p_extensions);
  42. }
  43. }
  44. String ResourceImporterImageFont::get_save_extension() const {
  45. return "fontdata";
  46. }
  47. String ResourceImporterImageFont::get_resource_type() const {
  48. return "FontFile";
  49. }
  50. bool ResourceImporterImageFont::get_option_visibility(const String &p_path, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
  51. return true;
  52. }
  53. void ResourceImporterImageFont::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const {
  54. r_options->push_back(ImportOption(PropertyInfo(Variant::PACKED_STRING_ARRAY, "character_ranges"), Vector<String>()));
  55. r_options->push_back(ImportOption(PropertyInfo(Variant::PACKED_STRING_ARRAY, "kerning_pairs"), Vector<String>()));
  56. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "columns", PROPERTY_HINT_RANGE, "1,1024,1,or_greater"), 1));
  57. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "rows", PROPERTY_HINT_RANGE, "1,1024,1,or_greater"), 1));
  58. r_options->push_back(ImportOption(PropertyInfo(Variant::RECT2I, "image_margin"), Rect2i()));
  59. r_options->push_back(ImportOption(PropertyInfo(Variant::RECT2I, "character_margin"), Rect2i()));
  60. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "ascent"), 0));
  61. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "descent"), 0));
  62. r_options->push_back(ImportOption(PropertyInfo(Variant::ARRAY, "fallbacks", PROPERTY_HINT_ARRAY_TYPE, MAKE_RESOURCE_TYPE_HINT("Font")), Array()));
  63. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "compress"), true));
  64. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "scaling_mode", PROPERTY_HINT_ENUM, "Disabled,Enabled (Integer),Enabled (Fractional)"), TextServer::FIXED_SIZE_SCALE_ENABLED));
  65. }
  66. Error ResourceImporterImageFont::import(const String &p_source_file, const String &p_save_path, const HashMap<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) {
  67. print_verbose("Importing image font from: " + p_source_file);
  68. int columns = p_options["columns"];
  69. int rows = p_options["rows"];
  70. int ascent = p_options["ascent"];
  71. int descent = p_options["descent"];
  72. Vector<String> ranges = p_options["character_ranges"];
  73. Vector<String> kern = p_options["kerning_pairs"];
  74. Array fallbacks = p_options["fallbacks"];
  75. Rect2i img_margin = p_options["image_margin"];
  76. Rect2i char_margin = p_options["character_margin"];
  77. TextServer::FixedSizeScaleMode smode = (TextServer::FixedSizeScaleMode)p_options["scaling_mode"].operator int();
  78. Ref<Image> img;
  79. img.instantiate();
  80. Error err = ImageLoader::load_image(p_source_file, img);
  81. ERR_FAIL_COND_V_MSG(err != OK, ERR_FILE_CANT_READ, vformat("Can't load font texture: \"%s\".", p_source_file));
  82. ERR_FAIL_COND_V_MSG(columns <= 0, ERR_FILE_CANT_READ, vformat("Columns (%d) must be positive.", columns));
  83. ERR_FAIL_COND_V_MSG(rows <= 0, ERR_FILE_CANT_READ, vformat("Rows (%d) must be positive.", rows));
  84. int count = columns * rows;
  85. int chr_cell_width = (img->get_width() - img_margin.position.x - img_margin.size.x) / columns;
  86. int chr_cell_height = (img->get_height() - img_margin.position.y - img_margin.size.y) / rows;
  87. ERR_FAIL_COND_V_MSG(chr_cell_width <= 0 || chr_cell_height <= 0, ERR_FILE_CANT_READ, "Image margin too big.");
  88. int chr_width = chr_cell_width - char_margin.position.x - char_margin.size.x;
  89. int chr_height = chr_cell_height - char_margin.position.y - char_margin.size.y;
  90. ERR_FAIL_COND_V_MSG(chr_width <= 0 || chr_height <= 0, ERR_FILE_CANT_READ, "Character margin too big.");
  91. Ref<FontFile> font;
  92. font.instantiate();
  93. font->set_antialiasing(TextServer::FONT_ANTIALIASING_NONE);
  94. font->set_generate_mipmaps(false);
  95. font->set_multichannel_signed_distance_field(false);
  96. font->set_fixed_size(chr_height);
  97. font->set_subpixel_positioning(TextServer::SUBPIXEL_POSITIONING_DISABLED);
  98. font->set_force_autohinter(false);
  99. font->set_allow_system_fallback(false);
  100. font->set_hinting(TextServer::HINTING_NONE);
  101. font->set_oversampling(1.0f);
  102. font->set_fallbacks(fallbacks);
  103. font->set_texture_image(0, Vector2i(chr_height, 0), 0, img);
  104. font->set_fixed_size_scale_mode(smode);
  105. int32_t pos = 0;
  106. for (const String &range : ranges) {
  107. int32_t start = -1;
  108. int32_t end = -1;
  109. int chr_adv = 0;
  110. Vector2i chr_off;
  111. {
  112. enum RangeParseStep {
  113. STEP_START_BEGIN,
  114. STEP_START_READ_HEX,
  115. STEP_START_READ_DEC,
  116. STEP_END_BEGIN,
  117. STEP_END_READ_HEX,
  118. STEP_END_READ_DEC,
  119. STEP_ADVANCE_BEGIN,
  120. STEP_OFF_X_BEGIN,
  121. STEP_OFF_Y_BEGIN,
  122. STEP_FINISHED,
  123. };
  124. RangeParseStep step = STEP_START_BEGIN;
  125. String token;
  126. for (int c = 0; c < range.length(); c++) {
  127. switch (step) {
  128. case STEP_START_BEGIN:
  129. case STEP_END_BEGIN: {
  130. // Read range start/end first symbol.
  131. if (range[c] == 'U' || range[c] == 'u') {
  132. if ((c <= range.length() - 2) && range[c + 1] == '+') {
  133. token = String();
  134. if (step == STEP_START_BEGIN) {
  135. step = STEP_START_READ_HEX;
  136. } else {
  137. step = STEP_END_READ_HEX;
  138. }
  139. c++; // Skip "+".
  140. continue;
  141. }
  142. } else if (range[c] == '0') {
  143. if ((c <= range.length() - 2) && range[c + 1] == 'x') {
  144. token = String();
  145. if (step == STEP_START_BEGIN) {
  146. step = STEP_START_READ_HEX;
  147. } else {
  148. step = STEP_END_READ_HEX;
  149. }
  150. c++; // Skip "x".
  151. continue;
  152. }
  153. } else if (range[c] == '\'' || range[c] == '\"') {
  154. if ((c <= range.length() - 3) && (range[c + 2] == '\'' || range[c + 2] == '\"')) {
  155. token = String();
  156. if (step == STEP_START_BEGIN) {
  157. start = range.unicode_at(c + 1);
  158. step = STEP_END_BEGIN;
  159. } else {
  160. end = range.unicode_at(c + 1);
  161. step = STEP_ADVANCE_BEGIN;
  162. }
  163. c = c + 2; // Skip the rest or token.
  164. continue;
  165. }
  166. } else if (is_digit(range[c])) {
  167. // Read decimal value, start.
  168. c++;
  169. token = String();
  170. if (step == STEP_START_BEGIN) {
  171. step = STEP_START_READ_DEC;
  172. } else {
  173. step = STEP_END_READ_DEC;
  174. }
  175. token += range[c];
  176. continue;
  177. }
  178. [[fallthrough]];
  179. }
  180. case STEP_ADVANCE_BEGIN:
  181. case STEP_OFF_X_BEGIN:
  182. case STEP_OFF_Y_BEGIN: {
  183. // Read advance and offset.
  184. if (range[c] == ' ') {
  185. int next = range.find(" ", c + 1);
  186. if (next < c) {
  187. next = range.length();
  188. }
  189. if (step == STEP_OFF_X_BEGIN) {
  190. chr_off.x = range.substr(c + 1, next - (c + 1)).to_int();
  191. step = STEP_OFF_Y_BEGIN;
  192. } else if (step == STEP_OFF_Y_BEGIN) {
  193. chr_off.y = range.substr(c + 1, next - (c + 1)).to_int();
  194. step = STEP_FINISHED;
  195. } else {
  196. chr_adv = range.substr(c + 1, next - (c + 1)).to_int();
  197. step = STEP_OFF_X_BEGIN;
  198. }
  199. c = next - 1;
  200. continue;
  201. }
  202. } break;
  203. case STEP_START_READ_HEX:
  204. case STEP_END_READ_HEX: {
  205. // Read hexadecimal value.
  206. if (is_hex_digit(range[c])) {
  207. token += range[c];
  208. } else {
  209. if (step == STEP_START_READ_HEX) {
  210. start = token.hex_to_int();
  211. step = STEP_END_BEGIN;
  212. } else {
  213. end = token.hex_to_int();
  214. step = STEP_ADVANCE_BEGIN;
  215. }
  216. }
  217. } break;
  218. case STEP_START_READ_DEC:
  219. case STEP_END_READ_DEC: {
  220. // Read decimal value.
  221. if (is_digit(range[c])) {
  222. token += range[c];
  223. } else {
  224. if (step == STEP_START_READ_DEC) {
  225. start = token.to_int();
  226. step = STEP_END_BEGIN;
  227. } else {
  228. end = token.to_int();
  229. step = STEP_ADVANCE_BEGIN;
  230. }
  231. }
  232. } break;
  233. default: {
  234. WARN_PRINT(vformat("Invalid character \"%d\" in the range: \"%s\"", c, range));
  235. } break;
  236. }
  237. }
  238. if (end == -1) {
  239. end = start;
  240. }
  241. if (start == -1) {
  242. WARN_PRINT(vformat("Invalid range: \"%s\"", range));
  243. continue;
  244. }
  245. }
  246. for (int32_t idx = MIN(start, end); idx <= MAX(start, end); idx++) {
  247. ERR_FAIL_COND_V_MSG(pos >= count, ERR_CANT_CREATE, "Too many characters in range, should be " + itos(columns * rows));
  248. int x = pos % columns;
  249. int y = pos / columns;
  250. font->set_glyph_advance(0, chr_height, idx, Vector2(chr_width + chr_adv, 0));
  251. font->set_glyph_offset(0, Vector2i(chr_height, 0), idx, Vector2i(0, -0.5 * chr_height) + chr_off);
  252. font->set_glyph_size(0, Vector2i(chr_height, 0), idx, Vector2(chr_width, chr_height));
  253. font->set_glyph_uv_rect(0, Vector2i(chr_height, 0), idx, Rect2(img_margin.position.x + chr_cell_width * x + char_margin.position.x, img_margin.position.y + chr_cell_height * y + char_margin.position.y, chr_width, chr_height));
  254. font->set_glyph_texture_idx(0, Vector2i(chr_height, 0), idx, 0);
  255. pos++;
  256. }
  257. }
  258. for (const String &kp : kern) {
  259. const Vector<String> &kp_tokens = kp.split(" ");
  260. if (kp_tokens.size() != 3) {
  261. WARN_PRINT(vformat("Invalid kerning pairs string: \"%s\"", kp));
  262. continue;
  263. }
  264. int offset = kp_tokens[2].to_int();
  265. for (int a = 0; a < kp_tokens[0].length(); a++) {
  266. for (int b = 0; b < kp_tokens[1].length(); b++) {
  267. font->set_kerning(0, chr_height, Vector2i(kp_tokens[0].unicode_at(a), kp_tokens[1].unicode_at(b)), Vector2(offset, 0));
  268. }
  269. }
  270. }
  271. if (ascent > 0) {
  272. font->set_cache_ascent(0, chr_height, ascent);
  273. } else {
  274. font->set_cache_ascent(0, chr_height, 0.5 * chr_height);
  275. }
  276. if (descent > 0) {
  277. font->set_cache_descent(0, chr_height, descent);
  278. } else {
  279. font->set_cache_descent(0, chr_height, 0.5 * chr_height);
  280. }
  281. int flg = 0;
  282. if ((bool)p_options["compress"]) {
  283. flg |= ResourceSaver::SaverFlags::FLAG_COMPRESS;
  284. }
  285. print_verbose("Saving to: " + p_save_path + ".fontdata");
  286. err = ResourceSaver::save(font, p_save_path + ".fontdata", flg);
  287. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save font to file \"" + p_save_path + ".res\".");
  288. print_verbose("Done saving to: " + p_save_path + ".fontdata");
  289. return OK;
  290. }
  291. ResourceImporterImageFont::ResourceImporterImageFont() {
  292. }