thorvg_svg_in_ot.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /**************************************************************************/
  2. /* thorvg_svg_in_ot.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. #ifdef GDEXTENSION
  31. // Headers for building as GDExtension plug-in.
  32. #include <godot_cpp/classes/xml_parser.hpp>
  33. #include <godot_cpp/core/mutex_lock.hpp>
  34. #include <godot_cpp/godot.hpp>
  35. #include <godot_cpp/templates/vector.hpp>
  36. using namespace godot;
  37. #else
  38. // Headers for building as built-in module.
  39. #include "core/error/error_macros.h"
  40. #include "core/io/xml_parser.h"
  41. #include "core/os/memory.h"
  42. #include "core/os/os.h"
  43. #include "core/string/ustring.h"
  44. #include "core/typedefs.h"
  45. #include "core/variant/variant.h"
  46. #include "modules/modules_enabled.gen.h" // For svg.
  47. #endif
  48. #ifdef MODULE_SVG_ENABLED
  49. #include "thorvg_bounds_iterator.h"
  50. #include "thorvg_svg_in_ot.h"
  51. #include <freetype/otsvg.h>
  52. #include <ft2build.h>
  53. #include <math.h>
  54. #include <stdlib.h>
  55. FT_Error tvg_svg_in_ot_init(FT_Pointer *p_state) {
  56. *p_state = memnew(TVG_State);
  57. return FT_Err_Ok;
  58. }
  59. void tvg_svg_in_ot_free(FT_Pointer *p_state) {
  60. TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);
  61. memdelete(state);
  62. }
  63. FT_Error tvg_svg_in_ot_preset_slot(FT_GlyphSlot p_slot, FT_Bool p_cache, FT_Pointer *p_state) {
  64. TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);
  65. if (!state) {
  66. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized.");
  67. }
  68. MutexLock lock(state->mutex);
  69. FT_SVG_Document document = (FT_SVG_Document)p_slot->other;
  70. FT_Size_Metrics metrics = document->metrics;
  71. GL_State &gl_state = state->glyph_map[p_slot->glyph_index];
  72. if (!gl_state.ready) {
  73. Ref<XMLParser> parser;
  74. parser.instantiate();
  75. parser->_open_buffer((const uint8_t *)document->svg_document, document->svg_document_length);
  76. float aspect = 1.0f;
  77. String xml_body;
  78. while (parser->read() == OK) {
  79. if (parser->has_attribute("id")) {
  80. const String &gl_name = parser->get_named_attribute_value("id");
  81. if (gl_name.begins_with("glyph")) {
  82. int dot_pos = gl_name.find(".");
  83. int64_t gl_idx = gl_name.substr(5, (dot_pos > 0) ? dot_pos - 5 : -1).to_int();
  84. if (p_slot->glyph_index != gl_idx) {
  85. parser->skip_section();
  86. continue;
  87. }
  88. }
  89. }
  90. if (parser->get_node_type() == XMLParser::NODE_ELEMENT && parser->get_node_name() == "svg") {
  91. if (parser->has_attribute("viewBox")) {
  92. PackedStringArray vb = parser->get_named_attribute_value("viewBox").split(" ");
  93. if (vb.size() == 4) {
  94. aspect = vb[2].to_float() / vb[3].to_float();
  95. }
  96. }
  97. continue;
  98. }
  99. if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
  100. xml_body += vformat("<%s", parser->get_node_name());
  101. for (int i = 0; i < parser->get_attribute_count(); i++) {
  102. xml_body += vformat(" %s=\"%s\"", parser->get_attribute_name(i), parser->get_attribute_value(i));
  103. }
  104. xml_body += ">";
  105. } else if (parser->get_node_type() == XMLParser::NODE_TEXT) {
  106. xml_body += parser->get_node_data();
  107. } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END) {
  108. xml_body += vformat("</%s>", parser->get_node_name());
  109. }
  110. }
  111. String temp_xml_str = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1 1\">" + xml_body;
  112. CharString temp_xml = temp_xml_str.utf8();
  113. std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
  114. tvg::Result result = picture->load(temp_xml.get_data(), temp_xml.length(), "svg+xml", false);
  115. if (result != tvg::Result::Success) {
  116. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (bounds detection).");
  117. }
  118. float min_x = INFINITY, min_y = INFINITY, max_x = -INFINITY, max_y = -INFINITY;
  119. tvg_get_bounds(picture.get(), min_x, min_y, max_x, max_y);
  120. float new_h = (max_y - min_y);
  121. float new_w = (max_x - min_x);
  122. if (new_h * aspect >= new_w) {
  123. new_w = (new_h * aspect);
  124. } else {
  125. new_h = (new_w / aspect);
  126. }
  127. String xml_code_str = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"" + rtos(min_x) + " " + rtos(min_y) + " " + rtos(new_w) + " " + rtos(new_h) + "\">" + xml_body;
  128. gl_state.xml_code = xml_code_str.utf8();
  129. picture = tvg::Picture::gen();
  130. result = picture->load(gl_state.xml_code.get_data(), gl_state.xml_code.length(), "svg+xml", false);
  131. if (result != tvg::Result::Success) {
  132. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph metrics).");
  133. }
  134. float x_svg_to_out, y_svg_to_out;
  135. x_svg_to_out = (float)metrics.x_ppem / new_w;
  136. y_svg_to_out = (float)metrics.y_ppem / new_h;
  137. gl_state.m.e11 = (double)document->transform.xx / (1 << 16) * x_svg_to_out;
  138. gl_state.m.e12 = -(double)document->transform.xy / (1 << 16) * x_svg_to_out;
  139. gl_state.m.e21 = -(double)document->transform.yx / (1 << 16) * y_svg_to_out;
  140. gl_state.m.e22 = (double)document->transform.yy / (1 << 16) * y_svg_to_out;
  141. gl_state.m.e13 = (double)document->delta.x / 64 * new_w / metrics.x_ppem;
  142. gl_state.m.e23 = -(double)document->delta.y / 64 * new_h / metrics.y_ppem;
  143. gl_state.m.e31 = 0;
  144. gl_state.m.e32 = 0;
  145. gl_state.m.e33 = 1;
  146. result = picture->transform(gl_state.m);
  147. if (result != tvg::Result::Success) {
  148. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document.");
  149. }
  150. result = picture->bounds(&gl_state.x, &gl_state.y, &gl_state.w, &gl_state.h, true);
  151. if (result != tvg::Result::Success) {
  152. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to get SVG bounds.");
  153. }
  154. gl_state.bmp_y = -min_y * gl_state.h / new_h;
  155. gl_state.bmp_x = min_x * gl_state.w / new_w;
  156. gl_state.ready = true;
  157. }
  158. p_slot->bitmap_left = (FT_Int)gl_state.bmp_x;
  159. p_slot->bitmap_top = (FT_Int)gl_state.bmp_y;
  160. float tmp = ceil(gl_state.h);
  161. p_slot->bitmap.rows = (unsigned int)tmp;
  162. tmp = ceil(gl_state.w);
  163. p_slot->bitmap.width = (unsigned int)tmp;
  164. p_slot->bitmap.pitch = (int)p_slot->bitmap.width * 4;
  165. p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
  166. float metrics_width, metrics_height;
  167. float horiBearingX, horiBearingY;
  168. float vertBearingX, vertBearingY;
  169. metrics_width = (float)gl_state.w;
  170. metrics_height = (float)gl_state.h;
  171. horiBearingX = (float)gl_state.x;
  172. horiBearingY = (float)-gl_state.y;
  173. vertBearingX = p_slot->metrics.horiBearingX / 64.0f - p_slot->metrics.horiAdvance / 64.0f / 2;
  174. vertBearingY = (p_slot->metrics.vertAdvance / 64.0f - p_slot->metrics.height / 64.0f) / 2;
  175. tmp = roundf(metrics_width * 64);
  176. p_slot->metrics.width = (FT_Pos)tmp;
  177. tmp = roundf(metrics_height * 64);
  178. p_slot->metrics.height = (FT_Pos)tmp;
  179. p_slot->metrics.horiBearingX = (FT_Pos)(horiBearingX * 64);
  180. p_slot->metrics.horiBearingY = (FT_Pos)(horiBearingY * 64);
  181. p_slot->metrics.vertBearingX = (FT_Pos)(vertBearingX * 64);
  182. p_slot->metrics.vertBearingY = (FT_Pos)(vertBearingY * 64);
  183. if (p_slot->metrics.vertAdvance == 0) {
  184. p_slot->metrics.vertAdvance = (FT_Pos)(metrics_height * 1.2f * 64);
  185. }
  186. return FT_Err_Ok;
  187. }
  188. FT_Error tvg_svg_in_ot_render(FT_GlyphSlot p_slot, FT_Pointer *p_state) {
  189. TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);
  190. if (!state) {
  191. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized.");
  192. }
  193. MutexLock lock(state->mutex);
  194. if (!state->glyph_map.has(p_slot->glyph_index)) {
  195. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG glyph not loaded.");
  196. }
  197. GL_State &gl_state = state->glyph_map[p_slot->glyph_index];
  198. ERR_FAIL_COND_V_MSG(!gl_state.ready, FT_Err_Invalid_SVG_Document, "SVG glyph not ready.");
  199. std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
  200. tvg::Result res = picture->load(gl_state.xml_code.get_data(), gl_state.xml_code.length(), "svg+xml", false);
  201. if (res != tvg::Result::Success) {
  202. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph rendering).");
  203. }
  204. res = picture->transform(gl_state.m);
  205. if (res != tvg::Result::Success) {
  206. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document.");
  207. }
  208. std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen();
  209. res = sw_canvas->target((uint32_t *)p_slot->bitmap.buffer, (int)p_slot->bitmap.width, (int)p_slot->bitmap.width, (int)p_slot->bitmap.rows, tvg::SwCanvas::ARGB8888_STRAIGHT);
  210. if (res != tvg::Result::Success) {
  211. ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to create SVG canvas.");
  212. }
  213. res = sw_canvas->push(std::move(picture));
  214. if (res != tvg::Result::Success) {
  215. ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to set SVG canvas source.");
  216. }
  217. res = sw_canvas->draw();
  218. if (res != tvg::Result::Success) {
  219. ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to draw to SVG canvas.");
  220. }
  221. res = sw_canvas->sync();
  222. if (res != tvg::Result::Success) {
  223. ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to sync SVG canvas.");
  224. }
  225. state->glyph_map.erase(p_slot->glyph_index);
  226. p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
  227. p_slot->bitmap.num_grays = 256;
  228. p_slot->format = FT_GLYPH_FORMAT_BITMAP;
  229. return FT_Err_Ok;
  230. }
  231. SVG_RendererHooks tvg_svg_in_ot_hooks = {
  232. (SVG_Lib_Init_Func)tvg_svg_in_ot_init,
  233. (SVG_Lib_Free_Func)tvg_svg_in_ot_free,
  234. (SVG_Lib_Render_Func)tvg_svg_in_ot_render,
  235. (SVG_Lib_Preset_Slot_Func)tvg_svg_in_ot_preset_slot,
  236. };
  237. SVG_RendererHooks *get_tvg_svg_in_ot_hooks() {
  238. return &tvg_svg_in_ot_hooks;
  239. }
  240. #endif // MODULE_SVG_ENABLED