thorvg_svg_in_ot.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. #include "thorvg_svg_in_ot.h"
  31. #ifdef GDEXTENSION
  32. // Headers for building as GDExtension plug-in.
  33. #include <godot_cpp/classes/xml_parser.hpp>
  34. #include <godot_cpp/core/mutex_lock.hpp>
  35. #include <godot_cpp/godot.hpp>
  36. #include <godot_cpp/templates/vector.hpp>
  37. using namespace godot;
  38. #elif defined(GODOT_MODULE)
  39. // Headers for building as built-in module.
  40. #include "core/error/error_macros.h"
  41. #include "core/io/xml_parser.h"
  42. #include "core/os/memory.h"
  43. #include "core/os/os.h"
  44. #include "core/string/ustring.h"
  45. #include "core/typedefs.h"
  46. #include "core/variant/variant.h"
  47. #include "modules/modules_enabled.gen.h" // For svg, freetype.
  48. #endif
  49. #ifdef MODULE_SVG_ENABLED
  50. #ifdef MODULE_FREETYPE_ENABLED
  51. #include <freetype/otsvg.h>
  52. #include <ft2build.h>
  53. #include <cstdlib>
  54. FT_Error tvg_svg_in_ot_init(FT_Pointer *p_state) {
  55. *p_state = memnew(TVG_State);
  56. return FT_Err_Ok;
  57. }
  58. void tvg_svg_in_ot_free(FT_Pointer *p_state) {
  59. TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);
  60. memdelete(state);
  61. }
  62. static void construct_xml(Ref<XMLParser> &parser, double &r_embox_x, double &r_embox_y, String *p_xml, int64_t &r_tag_count) {
  63. if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
  64. *p_xml += vformat("<%s", parser->get_node_name());
  65. bool is_svg_tag = parser->get_node_name() == "svg";
  66. for (int i = 0; i < parser->get_attribute_count(); i++) {
  67. String aname = parser->get_attribute_name(i);
  68. String value = parser->get_attribute_value(i);
  69. if (is_svg_tag && aname == "viewBox") {
  70. PackedStringArray vb = value.split(" ");
  71. if (vb.size() == 4) {
  72. r_embox_x = vb[2].to_float();
  73. r_embox_y = vb[3].to_float();
  74. }
  75. } else if (is_svg_tag && aname == "width") {
  76. r_embox_x = value.to_float();
  77. } else if (is_svg_tag && aname == "height") {
  78. r_embox_y = value.to_float();
  79. } else {
  80. *p_xml += vformat(" %s=\"%s\"", aname, value);
  81. }
  82. }
  83. if (parser->is_empty()) {
  84. *p_xml += "/>";
  85. } else {
  86. *p_xml += ">";
  87. if (r_tag_count >= 0) {
  88. r_tag_count++;
  89. }
  90. }
  91. } else if (parser->get_node_type() == XMLParser::NODE_TEXT) {
  92. *p_xml += parser->get_node_data();
  93. } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END) {
  94. *p_xml += vformat("</%s>", parser->get_node_name());
  95. if (r_tag_count > 0) {
  96. r_tag_count--;
  97. }
  98. }
  99. }
  100. FT_Error tvg_svg_in_ot_preset_slot(FT_GlyphSlot p_slot, FT_Bool p_cache, FT_Pointer *p_state) {
  101. TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);
  102. if (!state) {
  103. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized.");
  104. }
  105. MutexLock lock(state->mutex);
  106. FT_SVG_Document document = (FT_SVG_Document)p_slot->other;
  107. FT_Size_Metrics metrics = document->metrics;
  108. GL_State &gl_state = state->glyph_map[p_slot->glyph_index];
  109. if (!gl_state.ready) {
  110. Ref<XMLParser> parser;
  111. parser.instantiate();
  112. parser->_open_buffer((const uint8_t *)document->svg_document, document->svg_document_length);
  113. String xml_body;
  114. double embox_x = document->units_per_EM;
  115. double embox_y = document->units_per_EM;
  116. TVG_DocumentCache &cache = state->document_map[document->svg_document];
  117. if (!cache.xml_body.is_empty()) {
  118. // If we have a cached document, that means we have already parsed it.
  119. // All node cache should be available.
  120. xml_body = cache.xml_body;
  121. embox_x = cache.embox_x;
  122. embox_y = cache.embox_y;
  123. ERR_FAIL_COND_V(!cache.node_caches.has(p_slot->glyph_index), FT_Err_Invalid_SVG_Document);
  124. Vector<TVG_NodeCache> &ncs = cache.node_caches[p_slot->glyph_index];
  125. uint64_t offset = 0;
  126. for (TVG_NodeCache &nc : ncs) {
  127. // Seek will call read() internally.
  128. if (parser->seek(nc.document_offset) == OK) {
  129. int64_t tag_count = 0;
  130. String xml_node;
  131. // We only parse the glyph node.
  132. do {
  133. construct_xml(parser, embox_x, embox_y, &xml_node, tag_count);
  134. } while (tag_count != 0 && parser->read() == OK);
  135. xml_body = xml_body.insert(nc.body_offset + offset, xml_node);
  136. offset += xml_node.length();
  137. }
  138. }
  139. } else {
  140. String xml_node;
  141. String xml_body_temp;
  142. String *p_xml = &xml_body_temp;
  143. int64_t tag_count = -1;
  144. bool is_in_defs = false;
  145. while (parser->read() == OK) {
  146. if (parser->get_node_type() == XMLParser::NODE_ELEMENT && parser->get_node_name().to_lower() == "defs") {
  147. is_in_defs = true;
  148. } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name().to_lower() == "defs") {
  149. is_in_defs = false;
  150. }
  151. if (!is_in_defs && parser->has_attribute("id")) {
  152. const String &gl_name = parser->get_named_attribute_value("id");
  153. if (gl_name.begins_with("glyph")) {
  154. #ifdef GDEXTENSION
  155. int dot_pos = gl_name.find(".");
  156. #else
  157. int dot_pos = gl_name.find_char('.');
  158. #endif // GDEXTENSION
  159. int64_t gl_idx = gl_name.substr(5, (dot_pos > 0) ? dot_pos - 5 : -1).to_int();
  160. TVG_NodeCache node_cache = TVG_NodeCache();
  161. node_cache.document_offset = parser->get_node_offset(),
  162. node_cache.body_offset = (uint64_t)cache.xml_body.length();
  163. cache.node_caches[gl_idx].push_back(node_cache);
  164. if (p_slot->glyph_index != gl_idx) {
  165. parser->skip_section();
  166. continue;
  167. }
  168. tag_count = 0;
  169. xml_node = "";
  170. p_xml = &xml_node;
  171. }
  172. }
  173. xml_body_temp = "";
  174. construct_xml(parser, embox_x, embox_y, p_xml, tag_count);
  175. if (xml_body_temp.length() > 0) {
  176. xml_body += xml_body_temp;
  177. cache.xml_body += xml_body_temp;
  178. continue;
  179. }
  180. if (tag_count == 0) {
  181. p_xml = &xml_body_temp;
  182. tag_count = -1;
  183. xml_body += xml_node;
  184. }
  185. }
  186. cache.embox_x = embox_x;
  187. cache.embox_y = embox_y;
  188. }
  189. std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
  190. gl_state.xml_code = xml_body.utf8();
  191. tvg::Result result = picture->load(gl_state.xml_code.get_data(), gl_state.xml_code.length(), "svg+xml", false);
  192. if (result != tvg::Result::Success) {
  193. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph metrics).");
  194. }
  195. float svg_width, svg_height;
  196. picture->size(&svg_width, &svg_height);
  197. double aspect_x = (svg_width > svg_height) ? svg_width / svg_height : 1.0;
  198. double aspect_y = (svg_width < svg_height) ? svg_height / svg_width : 1.0;
  199. result = picture->size(embox_x * aspect_x, embox_y * aspect_y);
  200. if (result != tvg::Result::Success) {
  201. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to resize SVG document.");
  202. }
  203. double scale = double(embox_x * aspect_x) / double(svg_width);
  204. double yoff = double(document->metrics.ascender + document->metrics.descender) / double(document->metrics.ascender);
  205. double x_svg_to_out = (double)metrics.x_ppem / embox_x / scale;
  206. double y_svg_to_out = (double)metrics.y_ppem / embox_y / scale;
  207. gl_state.m.e11 = (double)document->transform.xx / (1 << 16);
  208. gl_state.m.e12 = -(double)document->transform.xy / (1 << 16);
  209. gl_state.m.e21 = -(double)document->transform.yx / (1 << 16);
  210. gl_state.m.e22 = (double)document->transform.yy / (1 << 16);
  211. gl_state.m.e13 = (double)document->delta.x / 64 * embox_x / metrics.x_ppem * scale;
  212. gl_state.m.e23 = -(double)document->delta.y / 64 * embox_y / metrics.y_ppem * scale;
  213. gl_state.m.e31 = 0;
  214. gl_state.m.e32 = 0;
  215. gl_state.m.e33 = 1;
  216. result = picture->size(embox_x * aspect_x * x_svg_to_out, embox_y * aspect_y * y_svg_to_out);
  217. if (result != tvg::Result::Success) {
  218. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to resize SVG document.");
  219. }
  220. result = picture->transform(gl_state.m);
  221. if (result != tvg::Result::Success) {
  222. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document.");
  223. }
  224. picture->size(&gl_state.w, &gl_state.h);
  225. gl_state.x = (double(p_slot->metrics.horiAdvance) / 64.0 - gl_state.w) / 2.0;
  226. gl_state.y = -Math::ceil(gl_state.h * yoff);
  227. gl_state.ready = true;
  228. }
  229. p_slot->bitmap_left = (FT_Int)gl_state.x;
  230. p_slot->bitmap_top = (FT_Int)-gl_state.y;
  231. double tmpd = Math::ceil(gl_state.h);
  232. p_slot->bitmap.rows = (unsigned int)tmpd;
  233. tmpd = Math::ceil(gl_state.w);
  234. p_slot->bitmap.width = (unsigned int)tmpd;
  235. p_slot->bitmap.pitch = (int)p_slot->bitmap.width * 4;
  236. p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
  237. float metrics_width = (float)gl_state.w;
  238. float metrics_height = (float)gl_state.h;
  239. float horiBearingX = (float)gl_state.x;
  240. float horiBearingY = (float)-gl_state.y;
  241. float vertBearingX = p_slot->metrics.horiBearingX / 64.0f - p_slot->metrics.horiAdvance / 64.0f / 2;
  242. float vertBearingY = (p_slot->metrics.vertAdvance / 64.0f - p_slot->metrics.height / 64.0f) / 2;
  243. float tmpf = Math::round(metrics_width * 64);
  244. p_slot->metrics.width = (FT_Pos)tmpf;
  245. tmpf = Math::round(metrics_height * 64);
  246. p_slot->metrics.height = (FT_Pos)tmpf;
  247. p_slot->metrics.horiBearingX = (FT_Pos)(horiBearingX * 64);
  248. p_slot->metrics.horiBearingY = (FT_Pos)(horiBearingY * 64);
  249. p_slot->metrics.vertBearingX = (FT_Pos)(vertBearingX * 64);
  250. p_slot->metrics.vertBearingY = (FT_Pos)(vertBearingY * 64);
  251. if (p_slot->metrics.vertAdvance == 0) {
  252. p_slot->metrics.vertAdvance = (FT_Pos)(metrics_height * 1.2f * 64);
  253. }
  254. return FT_Err_Ok;
  255. }
  256. FT_Error tvg_svg_in_ot_render(FT_GlyphSlot p_slot, FT_Pointer *p_state) {
  257. TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);
  258. if (!state) {
  259. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized.");
  260. }
  261. MutexLock lock(state->mutex);
  262. if (!state->glyph_map.has(p_slot->glyph_index)) {
  263. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG glyph not loaded.");
  264. }
  265. GL_State &gl_state = state->glyph_map[p_slot->glyph_index];
  266. ERR_FAIL_COND_V_MSG(!gl_state.ready, FT_Err_Invalid_SVG_Document, "SVG glyph not ready.");
  267. std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
  268. tvg::Result res = picture->load(gl_state.xml_code.get_data(), gl_state.xml_code.length(), "svg+xml", false);
  269. if (res != tvg::Result::Success) {
  270. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph rendering).");
  271. }
  272. res = picture->size(gl_state.w, gl_state.h);
  273. if (res != tvg::Result::Success) {
  274. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to resize SVG document.");
  275. }
  276. res = picture->transform(gl_state.m);
  277. if (res != tvg::Result::Success) {
  278. ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document.");
  279. }
  280. std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen();
  281. 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::ARGB8888S);
  282. if (res != tvg::Result::Success) {
  283. ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to create SVG canvas.");
  284. }
  285. res = sw_canvas->push(std::move(picture));
  286. if (res != tvg::Result::Success) {
  287. ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to set SVG canvas source.");
  288. }
  289. res = sw_canvas->draw();
  290. if (res != tvg::Result::Success) {
  291. ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to draw to SVG canvas.");
  292. }
  293. res = sw_canvas->sync();
  294. if (res != tvg::Result::Success) {
  295. ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to sync SVG canvas.");
  296. }
  297. state->glyph_map.erase(p_slot->glyph_index);
  298. p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
  299. p_slot->bitmap.num_grays = 256;
  300. p_slot->format = FT_GLYPH_FORMAT_BITMAP;
  301. return FT_Err_Ok;
  302. }
  303. SVG_RendererHooks tvg_svg_in_ot_hooks = {
  304. (SVG_Lib_Init_Func)tvg_svg_in_ot_init,
  305. (SVG_Lib_Free_Func)tvg_svg_in_ot_free,
  306. (SVG_Lib_Render_Func)tvg_svg_in_ot_render,
  307. (SVG_Lib_Preset_Slot_Func)tvg_svg_in_ot_preset_slot,
  308. };
  309. SVG_RendererHooks *get_tvg_svg_in_ot_hooks() {
  310. return &tvg_svg_in_ot_hooks;
  311. }
  312. #endif // MODULE_FREETYPE_ENABLED
  313. #endif // MODULE_SVG_ENABLED