1/**************************************************************************/
2/* image_loader_svg.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
31#include "image_loader_svg.h"
32
33#include "core/os/memory.h"
34#include "core/variant/variant.h"
35
36#include <thorvg.h>
37
38HashMap<Color, Color> ImageLoaderSVG::forced_color_map = HashMap<Color, Color>();
39
40void ImageLoaderSVG::set_forced_color_map(const HashMap<Color, Color> &p_color_map) {
41 forced_color_map = p_color_map;
42}
43
44void ImageLoaderSVG::_replace_color_property(const HashMap<Color, Color> &p_color_map, const String &p_prefix, String &r_string) {
45 // Replace colors in the SVG based on what is passed in `p_color_map`.
46 // Used to change the colors of editor icons based on the used theme.
47 // The strings being replaced are typically of the form:
48 // fill="#5abbef"
49 // But can also be 3-letter codes, include alpha, be "none" or a named color
50 // string ("blue"). So we convert to Godot Color to compare with `p_color_map`.
51
52 const int prefix_len = p_prefix.length();
53 int pos = r_string.find(p_prefix);
54 while (pos != -1) {
55 pos += prefix_len; // Skip prefix.
56 int end_pos = r_string.find("\"", pos);
57 ERR_FAIL_COND_MSG(end_pos == -1, vformat("Malformed SVG string after property \"%s\".", p_prefix));
58 const String color_code = r_string.substr(pos, end_pos - pos);
59 if (color_code != "none" && !color_code.begins_with("url(")) {
60 const Color color = Color(color_code); // Handles both HTML codes and named colors.
61 if (p_color_map.has(color)) {
62 r_string = r_string.left(pos) + "#" + p_color_map[color].to_html(false) + r_string.substr(end_pos);
63 }
64 }
65 // Search for other occurrences.
66 pos = r_string.find(p_prefix, pos);
67 }
68}
69
70Ref<Image> ImageLoaderSVG::load_mem_svg(const uint8_t *p_svg, int p_size, float p_scale) {
71 Ref<Image> img;
72 img.instantiate();
73
74 Error err = create_image_from_utf8_buffer(img, p_svg, p_size, p_scale, false);
75 ERR_FAIL_COND_V(err, Ref<Image>());
76
77 return img;
78}
79
80Error ImageLoaderSVG::create_image_from_utf8_buffer(Ref<Image> p_image, const uint8_t *p_buffer, int p_buffer_size, float p_scale, bool p_upsample) {
81 ERR_FAIL_COND_V_MSG(Math::is_zero_approx(p_scale), ERR_INVALID_PARAMETER, "ImageLoaderSVG: Can't load SVG with a scale of 0.");
82
83 std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
84
85 tvg::Result result = picture->load((const char *)p_buffer, p_buffer_size, "svg", true);
86 if (result != tvg::Result::Success) {
87 return ERR_INVALID_DATA;
88 }
89 float fw, fh;
90 picture->size(&fw, &fh);
91
92 uint32_t width = MAX(1, round(fw * p_scale));
93 uint32_t height = MAX(1, round(fh * p_scale));
94
95 const uint32_t max_dimension = 16384;
96 if (width > max_dimension || height > max_dimension) {
97 WARN_PRINT(vformat(
98 String::utf8("ImageLoaderSVG: Target canvas dimensions %d×%d (with scale %.2f) exceed the max supported dimensions %d×%d. The target canvas will be scaled down."),
99 width, height, p_scale, max_dimension, max_dimension));
100 width = MIN(width, max_dimension);
101 height = MIN(height, max_dimension);
102 }
103
104 picture->size(width, height);
105
106 std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen();
107 // Note: memalloc here, be sure to memfree before any return.
108 uint32_t *buffer = (uint32_t *)memalloc(sizeof(uint32_t) * width * height);
109
110 tvg::Result res = sw_canvas->target(buffer, width, width, height, tvg::SwCanvas::ARGB8888S);
111 if (res != tvg::Result::Success) {
112 memfree(buffer);
113 ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't set target on ThorVG canvas.");
114 }
115
116 res = sw_canvas->push(std::move(picture));
117 if (res != tvg::Result::Success) {
118 memfree(buffer);
119 ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't insert ThorVG picture on canvas.");
120 }
121
122 res = sw_canvas->draw();
123 if (res != tvg::Result::Success) {
124 memfree(buffer);
125 ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't draw ThorVG pictures on canvas.");
126 }
127
128 res = sw_canvas->sync();
129 if (res != tvg::Result::Success) {
130 memfree(buffer);
131 ERR_FAIL_V_MSG(FAILED, "ImageLoaderSVG: Couldn't sync ThorVG canvas.");
132 }
133
134 Vector<uint8_t> image;
135 image.resize(width * height * sizeof(uint32_t));
136
137 for (uint32_t y = 0; y < height; y++) {
138 for (uint32_t x = 0; x < width; x++) {
139 uint32_t n = buffer[y * width + x];
140 const size_t offset = sizeof(uint32_t) * width * y + sizeof(uint32_t) * x;
141 image.write[offset + 0] = (n >> 16) & 0xff;
142 image.write[offset + 1] = (n >> 8) & 0xff;
143 image.write[offset + 2] = n & 0xff;
144 image.write[offset + 3] = (n >> 24) & 0xff;
145 }
146 }
147
148 res = sw_canvas->clear(true);
149 memfree(buffer);
150
151 p_image->set_data(width, height, false, Image::FORMAT_RGBA8, image);
152 return OK;
153}
154
155Error ImageLoaderSVG::create_image_from_utf8_buffer(Ref<Image> p_image, const PackedByteArray &p_buffer, float p_scale, bool p_upsample) {
156 return create_image_from_utf8_buffer(p_image, p_buffer.ptr(), p_buffer.size(), p_scale, p_upsample);
157}
158
159Error ImageLoaderSVG::create_image_from_string(Ref<Image> p_image, String p_string, float p_scale, bool p_upsample, const HashMap<Color, Color> &p_color_map) {
160 if (p_color_map.size()) {
161 _replace_color_property(p_color_map, "stop-color=\"", p_string);
162 _replace_color_property(p_color_map, "fill=\"", p_string);
163 _replace_color_property(p_color_map, "stroke=\"", p_string);
164 }
165
166 PackedByteArray bytes = p_string.to_utf8_buffer();
167
168 return create_image_from_utf8_buffer(p_image, bytes, p_scale, p_upsample);
169}
170
171void ImageLoaderSVG::get_recognized_extensions(List<String> *p_extensions) const {
172 p_extensions->push_back("svg");
173}
174
175Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) {
176 String svg = p_fileaccess->get_as_utf8_string();
177
178 Error err;
179 if (p_flags & FLAG_CONVERT_COLORS) {
180 err = create_image_from_string(p_image, svg, p_scale, false, forced_color_map);
181 } else {
182 err = create_image_from_string(p_image, svg, p_scale, false, HashMap<Color, Color>());
183 }
184
185 if (err != OK) {
186 return err;
187 } else if (p_image->is_empty()) {
188 return ERR_INVALID_DATA;
189 }
190
191 if (p_flags & FLAG_FORCE_LINEAR) {
192 p_image->srgb_to_linear();
193 }
194 return OK;
195}
196
197ImageLoaderSVG::ImageLoaderSVG() {
198 Image::_svg_scalable_mem_loader_func = load_mem_svg;
199}
200