resource_importer_imagefont.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 (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(ResourceUID::ID p_source_id, 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 remaining = 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_keep_rounding_remainders(true);
  99. font->set_force_autohinter(false);
  100. font->set_modulate_color_glyphs(false);
  101. font->set_allow_system_fallback(false);
  102. font->set_hinting(TextServer::HINTING_NONE);
  103. font->set_fallbacks(fallbacks);
  104. font->set_texture_image(0, Vector2i(chr_height, 0), 0, img);
  105. font->set_fixed_size_scale_mode(smode);
  106. int32_t pos = 0;
  107. for (const String &range : ranges) {
  108. Vector<int32_t> list;
  109. int32_t start = -1;
  110. int32_t end = -1;
  111. int chr_adv = 0;
  112. Vector2i chr_off;
  113. {
  114. enum RangeParseStep {
  115. STEP_START_BEGIN,
  116. STEP_START_READ_HEX,
  117. STEP_START_READ_DEC,
  118. STEP_END_BEGIN,
  119. STEP_END_READ_HEX,
  120. STEP_END_READ_DEC,
  121. STEP_ADVANCE_BEGIN,
  122. STEP_OFF_X_BEGIN,
  123. STEP_OFF_Y_BEGIN,
  124. STEP_FINISHED,
  125. };
  126. RangeParseStep step = STEP_START_BEGIN;
  127. String token;
  128. for (int c = 0; c < range.length(); c++) {
  129. switch (step) {
  130. case STEP_START_BEGIN:
  131. case STEP_END_BEGIN: {
  132. // Read range start/end first symbol.
  133. if (range[c] == 'U' || range[c] == 'u') {
  134. if ((c <= range.length() - 2) && range[c + 1] == '+') {
  135. token = String();
  136. if (step == STEP_START_BEGIN) {
  137. step = STEP_START_READ_HEX;
  138. } else {
  139. step = STEP_END_READ_HEX;
  140. }
  141. c++; // Skip "+".
  142. continue;
  143. }
  144. } else if (range[c] == '0' && (c <= range.length() - 2) && (range[c + 1] == 'x' || range[c + 1] == 'X')) {
  145. // Read hexadecimal value, start.
  146. token = String();
  147. if (step == STEP_START_BEGIN) {
  148. step = STEP_START_READ_HEX;
  149. } else {
  150. step = STEP_END_READ_HEX;
  151. }
  152. c++; // Skip "x".
  153. continue;
  154. } else if (range[c] == '\'' || range[c] == '\"') {
  155. if ((c <= range.length() - 3) && (range[c + 2] == '\'' || range[c + 2] == '\"')) {
  156. token = String();
  157. if (step == STEP_START_BEGIN) {
  158. start = range.unicode_at(c + 1);
  159. if ((c <= range.length() - 4) && (range[c + 3] == ',')) {
  160. list.push_back(start);
  161. step = STEP_START_BEGIN;
  162. } else {
  163. step = STEP_END_BEGIN;
  164. }
  165. } else {
  166. end = range.unicode_at(c + 1);
  167. step = STEP_ADVANCE_BEGIN;
  168. }
  169. c = c + 2; // Skip the rest or token.
  170. continue;
  171. }
  172. } else if (is_digit(range[c])) {
  173. // Read decimal value, start.
  174. token = String();
  175. token += range[c];
  176. if (step == STEP_START_BEGIN) {
  177. step = STEP_START_READ_DEC;
  178. } else {
  179. step = STEP_END_READ_DEC;
  180. }
  181. continue;
  182. }
  183. [[fallthrough]];
  184. }
  185. case STEP_ADVANCE_BEGIN:
  186. case STEP_OFF_X_BEGIN:
  187. case STEP_OFF_Y_BEGIN: {
  188. // Read advance and offset.
  189. if (range[c] == ' ') {
  190. int next = range.find_char(' ', c + 1);
  191. if (next < c) {
  192. next = range.length();
  193. }
  194. if (step == STEP_OFF_X_BEGIN) {
  195. chr_off.x = range.substr(c + 1, next - (c + 1)).to_int();
  196. step = STEP_OFF_Y_BEGIN;
  197. } else if (step == STEP_OFF_Y_BEGIN) {
  198. chr_off.y = range.substr(c + 1, next - (c + 1)).to_int();
  199. step = STEP_FINISHED;
  200. } else {
  201. chr_adv = range.substr(c + 1, next - (c + 1)).to_int();
  202. step = STEP_OFF_X_BEGIN;
  203. }
  204. c = next - 1;
  205. continue;
  206. }
  207. } break;
  208. case STEP_START_READ_HEX:
  209. case STEP_END_READ_HEX: {
  210. // Read hexadecimal value.
  211. if (is_hex_digit(range[c])) {
  212. token += range[c];
  213. } else {
  214. if (step == STEP_START_READ_HEX) {
  215. start = token.hex_to_int();
  216. if (range[c] == ',') {
  217. list.push_back(start);
  218. step = STEP_START_BEGIN;
  219. } else {
  220. step = STEP_END_BEGIN;
  221. }
  222. } else {
  223. end = token.hex_to_int();
  224. step = STEP_ADVANCE_BEGIN;
  225. c--;
  226. }
  227. }
  228. } break;
  229. case STEP_START_READ_DEC:
  230. case STEP_END_READ_DEC: {
  231. // Read decimal value.
  232. if (is_digit(range[c])) {
  233. token += range[c];
  234. } else {
  235. if (step == STEP_START_READ_DEC) {
  236. start = token.to_int();
  237. if (range[c] == ',') {
  238. list.push_back(start);
  239. step = STEP_START_BEGIN;
  240. } else {
  241. step = STEP_END_BEGIN;
  242. }
  243. } else {
  244. end = token.to_int();
  245. step = STEP_ADVANCE_BEGIN;
  246. c--;
  247. }
  248. }
  249. } break;
  250. default: {
  251. WARN_PRINT(vformat("Invalid character \"%d\" in the range: \"%s\"", c, range));
  252. } break;
  253. }
  254. }
  255. if (step == STEP_START_READ_HEX) {
  256. start = token.hex_to_int();
  257. } else if (step == STEP_START_READ_DEC) {
  258. start = token.to_int();
  259. } else if (step == STEP_END_READ_HEX) {
  260. end = token.hex_to_int();
  261. } else if (step == STEP_END_READ_DEC) {
  262. end = token.to_int();
  263. }
  264. if (end == -1) {
  265. end = start;
  266. }
  267. if (!list.is_empty() && end != list[list.size() - 1]) {
  268. list.push_back(end);
  269. }
  270. if (start == -1) {
  271. WARN_PRINT(vformat("Invalid range: \"%s\"", range));
  272. continue;
  273. }
  274. }
  275. if (!list.is_empty()) {
  276. ERR_FAIL_COND_V_MSG(list.size() > remaining, ERR_CANT_CREATE, vformat("Too many characters in range \"%s\", got %d but expected be %d.", range, list.size(), remaining));
  277. for (int32_t idx : list) {
  278. int x = pos % columns;
  279. int y = pos / columns;
  280. font->set_glyph_advance(0, chr_height, idx, Vector2(chr_width + chr_adv, 0));
  281. font->set_glyph_offset(0, Vector2i(chr_height, 0), idx, Vector2i(0, -0.5 * chr_height) + chr_off);
  282. font->set_glyph_size(0, Vector2i(chr_height, 0), idx, Vector2(chr_width, chr_height));
  283. 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));
  284. font->set_glyph_texture_idx(0, Vector2i(chr_height, 0), idx, 0);
  285. pos++;
  286. }
  287. remaining -= list.size();
  288. } else {
  289. ERR_FAIL_COND_V_MSG(Math::abs(end - start) > remaining, ERR_CANT_CREATE, vformat("Too many characters in range \"%s\", got %d but expected %d.", range, Math::abs(end - start), remaining));
  290. for (int32_t idx = MIN(start, end); idx <= MAX(start, end); idx++) {
  291. int x = pos % columns;
  292. int y = pos / columns;
  293. font->set_glyph_advance(0, chr_height, idx, Vector2(chr_width + chr_adv, 0));
  294. font->set_glyph_offset(0, Vector2i(chr_height, 0), idx, Vector2i(0, -0.5 * chr_height) + chr_off);
  295. font->set_glyph_size(0, Vector2i(chr_height, 0), idx, Vector2(chr_width, chr_height));
  296. 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));
  297. font->set_glyph_texture_idx(0, Vector2i(chr_height, 0), idx, 0);
  298. pos++;
  299. }
  300. remaining -= abs(end - start);
  301. }
  302. }
  303. for (const String &kp : kern) {
  304. const Vector<String> &kp_tokens = kp.split(" ");
  305. if (kp_tokens.size() != 3) {
  306. WARN_PRINT(vformat("Invalid kerning pairs string: \"%s\"", kp));
  307. continue;
  308. }
  309. String from_tokens;
  310. for (int i = 0; i < kp_tokens[0].length(); i++) {
  311. if (i <= kp_tokens[0].length() - 6 && kp_tokens[0][i] == '\\' && kp_tokens[0][i + 1] == 'u' && is_hex_digit(kp_tokens[0][i + 2]) && is_hex_digit(kp_tokens[0][i + 3]) && is_hex_digit(kp_tokens[0][i + 4]) && is_hex_digit(kp_tokens[0][i + 5])) {
  312. char32_t charcode = kp_tokens[0].substr(i + 2, 4).hex_to_int();
  313. from_tokens += charcode;
  314. i += 5;
  315. } else {
  316. from_tokens += kp_tokens[0][i];
  317. }
  318. }
  319. String to_tokens;
  320. for (int i = 0; i < kp_tokens[1].length(); i++) {
  321. if (i <= kp_tokens[1].length() - 6 && kp_tokens[1][i] == '\\' && kp_tokens[1][i + 1] == 'u' && is_hex_digit(kp_tokens[1][i + 2]) && is_hex_digit(kp_tokens[1][i + 3]) && is_hex_digit(kp_tokens[1][i + 4]) && is_hex_digit(kp_tokens[1][i + 5])) {
  322. char32_t charcode = kp_tokens[1].substr(i + 2, 4).hex_to_int();
  323. to_tokens += charcode;
  324. i += 5;
  325. } else {
  326. to_tokens += kp_tokens[1][i];
  327. }
  328. }
  329. int offset = kp_tokens[2].to_int();
  330. for (int a = 0; a < from_tokens.length(); a++) {
  331. for (int b = 0; b < to_tokens.length(); b++) {
  332. font->set_kerning(0, chr_height, Vector2i(from_tokens.unicode_at(a), to_tokens.unicode_at(b)), Vector2(offset, 0));
  333. }
  334. }
  335. }
  336. if (ascent > 0) {
  337. font->set_cache_ascent(0, chr_height, ascent);
  338. } else {
  339. font->set_cache_ascent(0, chr_height, 0.5 * chr_height);
  340. }
  341. if (descent > 0) {
  342. font->set_cache_descent(0, chr_height, descent);
  343. } else {
  344. font->set_cache_descent(0, chr_height, 0.5 * chr_height);
  345. }
  346. int flg = 0;
  347. if ((bool)p_options["compress"]) {
  348. flg |= ResourceSaver::SaverFlags::FLAG_COMPRESS;
  349. }
  350. print_verbose("Saving to: " + p_save_path + ".fontdata");
  351. err = ResourceSaver::save(font, p_save_path + ".fontdata", flg);
  352. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save font to file \"" + p_save_path + ".res\".");
  353. print_verbose("Done saving to: " + p_save_path + ".fontdata");
  354. return OK;
  355. }