Blender V5.3
grease_pencil_io_export_svg.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2024 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include "BLI_bounds.hh"
6#include "BLI_color_types.hh"
7#include "BLI_math_color_c.hh"
8#include "BLI_string_utf8.hh"
9#include "BLI_vector.hh"
10
11#include "BKE_curves.hh"
12#include "BKE_grease_pencil.hh"
13#include "BKE_scene.hh"
14
15#include "DNA_object_types.h"
16#include "DNA_scene_types.h"
17
19
21#include "GEO_set_curve_type.hh"
22
24
25#include <fmt/core.h>
26#include <fmt/format.h>
27#include <optional>
28#include <pugixml.hpp>
29
30#ifdef WIN32
31# include "utfconv.hh"
32#endif
33
37
39
40constexpr const char *svg_exporter_name = "SVG Export for Grease Pencil";
41constexpr const char *svg_exporter_version = "v2.1";
42
43static std::string rgb_to_hexstr(const float color[3])
44{
45 uchar rgb[3];
47 return fmt::format("#{:02X}{:02X}{:02X}", rgb[0], rgb[1], rgb[2]);
48}
49
50static void write_stroke_color_attribute(pugi::xml_node node,
51 const ColorGeometry4f &stroke_color,
52 const float stroke_opacity,
53 const std::optional<float> miter_limit_angle,
54 const bool round_cap)
55{
57 linearrgb_to_srgb_v3_v3(color, stroke_color);
58 std::string stroke_hex = rgb_to_hexstr(color);
59
60 node.append_attribute("stroke").set_value(stroke_hex.c_str());
61 node.append_attribute("stroke-opacity").set_value(stroke_color.a * stroke_opacity);
62
63 node.append_attribute("fill").set_value("none");
64 node.append_attribute("stroke-linecap").set_value(round_cap ? "round" : "square");
65
66 if (miter_limit_angle) {
67 if (*miter_limit_angle <= GP_STROKE_MITER_ANGLE_ROUND) {
68 node.append_attribute("stroke-linejoin").set_value("round");
69 }
70 else if (*miter_limit_angle >= GP_STROKE_MITER_ANGLE_BEVEL) {
71 node.append_attribute("stroke-linejoin").set_value("bevel");
72 }
73 else {
74 /* Convert the Miter angle to the Miter limit. */
75 const float miter_limit = 1.0f / math::sin(*miter_limit_angle / 2.0f);
76
77 node.append_attribute("stroke-linejoin").set_value("miter");
78 node.append_attribute("stroke-miterlimit").set_value(miter_limit);
79 }
80 }
81}
82
83static void write_fill_color_attribute(pugi::xml_node node,
84 const ColorGeometry4f &fill_color,
85 const float layer_opacity)
86{
88 linearrgb_to_srgb_v3_v3(color, fill_color);
89 std::string stroke_hex = rgb_to_hexstr(color);
90
91 node.append_attribute("fill").set_value(stroke_hex.c_str());
92 node.append_attribute("stroke").set_value("none");
93 node.append_attribute("fill-opacity").set_value(fill_color.a * layer_opacity);
94}
95
96static void write_rect(pugi::xml_node node,
97 const float x,
98 const float y,
99 const float width,
100 const float height,
101 const float thickness,
102 const std::string &hexcolor)
103{
104 pugi::xml_node rect_node = node.append_child("rect");
105 rect_node.append_attribute("x").set_value(x);
106 rect_node.append_attribute("y").set_value(y);
107 rect_node.append_attribute("width").set_value(width);
108 rect_node.append_attribute("height").set_value(height);
109 rect_node.append_attribute("fill").set_value("none");
110 if (thickness > 0.0f) {
111 rect_node.append_attribute("stroke").set_value(hexcolor.c_str());
112 rect_node.append_attribute("stroke-width").set_value(thickness);
113 }
114}
115
117 uint64_t _node_uuid = 0;
118
119 std::string get_node_uuid_string();
120
121 public:
123
124 pugi::xml_document main_doc_;
125
127 void export_grease_pencil_objects(pugi::xml_node node, int frame_number);
128 void export_grease_pencil_layer(pugi::xml_node node,
129 const Object &object,
131 const bke::greasepencil::Drawing &drawing);
132
134 pugi::xml_node write_main_node();
135 pugi::xml_node write_animation_node(pugi::xml_node parent_node,
136 IndexMask frames,
137 float duration);
138 pugi::xml_node write_path(pugi::xml_node node,
139 const float4x4 &transform,
140 const Span<float3> positions,
141 const std::optional<Span<float3>> positions_left,
142 const std::optional<Span<float3>> positions_right,
143 const OffsetIndices<int> points_by_curve,
144 const Span<int> shape,
145 const VArray<bool> &cyclic,
146 const VArray<int8_t> &types,
147 std::optional<float> width);
148
149 bool write_to_file(StringRefNull filepath);
150};
151
152std::string SVGExporter::get_node_uuid_string()
153{
154 std::string id = fmt::format(".uuid_{:#x}", this->_node_uuid++);
155 return id;
156}
157
159{
160 this->_node_uuid = 0;
161
162 switch (params_.frame_mode) {
164 const int frame_number = scene.r.cfra;
165 this->prepare_render_params(scene, frame_number);
166
167 this->write_document_header();
168 pugi::xml_node main_node = this->write_main_node();
169
170 this->export_grease_pencil_objects(main_node, frame_number);
171
172 const bool write_success = this->write_to_file(filepath);
173 return write_success ? ExportStatus::Ok : ExportStatus::FileWriteError;
174 }
177 const bool selection_only = params_.frame_mode == ExportParams::FrameMode::Selected;
178 const int orig_frame = scene.r.cfra;
179
180 IndexMask frames = IndexMask(IndexRange(scene.r.sfra, scene.r.efra - scene.r.sfra + 1));
181
182 IndexMaskMemory memory;
183 if (selection_only) {
185 if (!ob_eval || ob_eval->type != OB_GREASE_PENCIL) {
187 }
188 const GreasePencil &grease_pencil = *id_cast<GreasePencil *>(ob_eval->data);
189 frames = IndexMask::from_predicate(frames, memory, [&](const int frame_number) {
190 return this->is_selected_frame(grease_pencil, frame_number);
191 });
192 }
193
194 if (frames.is_empty()) {
196 }
197
198 this->prepare_render_params(scene, frames.first());
199
200 this->write_document_header();
201 pugi::xml_node main_node = this->write_main_node();
202
203 /* Put frames in a hidden group. They are referenced later by a `<use>-node` that displays
204 * them in order. Use a group rather than a `<defs>-node` because some graphics applications
205 * don't expose those to users making it hard for them to work with the file.
206 */
207 pugi::xml_node frames_group_node = main_node.append_child("g");
208 frames_group_node.append_attribute("id").set_value("blender_frames");
209 frames_group_node.append_attribute("display").set_value("none");
210
211 const int frame_count = frames.size();
212 const float duration = scene.r.frs_sec_base * frame_count / scene.r.frs_sec;
213
214 frames.foreach_index([&](const int frame_number) {
215 scene.r.cfra = frame_number;
217 this->prepare_render_params(scene, frame_number);
218 this->export_grease_pencil_objects(frames_group_node, frame_number);
219 });
220
221 /* Back to original frame. */
222 scene.r.cfra = orig_frame;
225
226 this->write_animation_node(main_node, frames, duration);
227
228 const bool write_success = this->write_to_file(filepath);
229 return write_success ? ExportStatus::Ok : ExportStatus::FileWriteError;
230 }
231 default:
234 }
235}
236
237static std::string frame_name(int frame_number)
238{
239 std::string frametxt = "blender_frame." + std::to_string(frame_number);
240 return frametxt;
241}
242
243void SVGExporter::export_grease_pencil_objects(pugi::xml_node node, const int frame_number)
244{
246
247 const bool is_clipping = camera_persmat_ && params_.use_clip_camera;
248
250
251 /* Camera clipping. */
252 if (is_clipping) {
253 pugi::xml_node clip_node = node.append_child("clipPath");
254 clip_node.append_attribute("id").set_value(
255 ("clip-path." + std::to_string(frame_number)).c_str());
256
257 write_rect(clip_node, 0, 0, camera_rect_.size().x, camera_rect_.size().y, 0.0f, "#000000");
258 }
259
260 pugi::xml_node frame_node = node.append_child("g");
261 frame_node.append_attribute("id").set_value(frame_name(frame_number).c_str());
262
263 /* Clip area. */
264 if (is_clipping) {
265 frame_node.append_attribute("clip-path")
266 .set_value(("url(#clip-path." + std::to_string(frame_number) + ")").c_str());
267 }
268
269 for (const ObjectInfo &info : objects) {
270 const Object *ob = info.object;
271
272 pugi::xml_node ob_node = frame_node.append_child("g");
273
274 char obtxt[15 + (MAX_ID_NAME - 2) + 1 + 11 + 1]; /* Final +1 for the null terminator. */
275 SNPRINTF_UTF8(obtxt, "blender_object.%s.%d", ob->id.name + 2, frame_number);
276 std::string object_id = std::string(obtxt) + this->get_node_uuid_string();
277 ob_node.append_attribute("id").set_value(object_id.c_str());
278
279 /* Use evaluated version to get strokes with modifiers. */
280 const Object *ob_eval = DEG_get_evaluated(context_.depsgraph, ob);
281 BLI_assert(ob_eval->type == OB_GREASE_PENCIL);
282 const GreasePencil *grease_pencil_eval = id_cast<const GreasePencil *>(ob_eval->data);
283
284 for (const bke::greasepencil::Layer *layer : grease_pencil_eval->layers()) {
285 if (!layer->is_visible()) {
286 continue;
287 }
288 const Drawing *drawing = grease_pencil_eval->get_drawing_at(*layer, frame_number);
289 if (drawing == nullptr) {
290 continue;
291 }
292
293 /* Layer node. */
294 pugi::xml_node layer_node = ob_node.append_child("g");
295 std::string layer_node_id = "layer." + layer->name() + this->get_node_uuid_string();
296 layer_node.append_attribute("id").set_value(layer_node_id.c_str());
297
298 const bke::CurvesGeometry &curves = drawing->strokes();
299 /* Convert NURBS and Catmull Rom to bezier then export. */
300 if (curves.has_curve_with_type({CURVE_TYPE_CATMULL_ROM, CURVE_TYPE_NURBS})) {
301 IndexMaskMemory memory;
302 const IndexMask non_poly_selection = curves.indices_for_curve_type(CURVE_TYPE_POLY, memory)
303 .complement(curves.curves_range(), memory);
304
306 options.convert_bezier_handles_to_poly_points = false;
307 options.convert_bezier_handles_to_catmull_rom_points = false;
308 options.keep_bezier_shape_as_nurbs = true;
309 options.keep_catmull_rom_shape_as_nurbs = true;
310
311 Drawing export_drawing;
313 curves, non_poly_selection, CURVE_TYPE_BEZIER, {}, options);
314 export_drawing.tag_topology_changed();
315 export_grease_pencil_layer(layer_node, *ob_eval, *layer, export_drawing);
316 }
317 else {
318 export_grease_pencil_layer(layer_node, *ob_eval, *layer, *drawing);
319 }
320 }
321 }
322}
323
324void SVGExporter::export_grease_pencil_layer(pugi::xml_node layer_node,
325 const Object &object,
327 const bke::greasepencil::Drawing &drawing)
328{
330
331 const float4x4 layer_to_world = layer.to_world_space(object);
332
333 auto write_shape = [&](const Span<float3> positions,
334 const std::optional<Span<float3>> positions_left,
335 const std::optional<Span<float3>> positions_right,
336 const OffsetIndices<int> points_by_curve,
337 const Span<int> shape,
338 const VArray<bool> &cyclic,
339 const VArray<int8_t> &types,
340 const ColorGeometry4f &color,
341 const float opacity,
342 const std::optional<float> width,
343 const std::optional<float> miter_limit_angle,
344 const bool round_cap,
345 const bool is_outline) {
346 pugi::xml_node element_node = write_path(layer_node,
347 layer_to_world,
348 positions,
349 positions_left,
350 positions_right,
351 points_by_curve,
352 shape,
353 cyclic,
354 types,
355 width);
356
357 if (is_outline) {
358 write_fill_color_attribute(element_node, color, opacity);
359 /* Outlines might self-overlap which creates visual holes with the `even-odd` fill rule. */
360 element_node.append_attribute("fill-rule").set_value("nonzero");
361 }
362 else {
363 element_node.append_attribute("fill-rule").set_value("evenodd");
364 if (width) {
365 write_stroke_color_attribute(element_node, color, opacity, miter_limit_angle, round_cap);
366 }
367 else {
368 write_fill_color_attribute(element_node, color, opacity);
369 }
370 }
371 };
372
373 foreach_shape_in_layer(object, layer, drawing, write_shape);
374}
375
377{
378 /* Add a custom document declaration node. */
379 pugi::xml_node decl = main_doc_.prepend_child(pugi::node_declaration);
380 decl.append_attribute("version") = "1.0";
381 decl.append_attribute("encoding") = "UTF-8";
382
383 pugi::xml_node comment = main_doc_.append_child(pugi::node_comment);
384 std::string txt = std::string(" Generator: Blender, ") + svg_exporter_name + " - " +
386 comment.set_value(txt.c_str());
387
388 pugi::xml_node doctype = main_doc_.append_child(pugi::node_doctype);
389 doctype.set_value(
390 "svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" "
391 "\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"");
392}
393
395{
396 pugi::xml_node main_node = main_doc_.append_child("svg");
397 main_node.append_attribute("version").set_value("1.1");
398 main_node.append_attribute("x").set_value("0px");
399 main_node.append_attribute("y").set_value("0px");
400 main_node.append_attribute("xmlns").set_value("http://www.w3.org/2000/svg");
401
402 std::string width, height;
403
404 if (camera_persmat_) {
405 width = std::to_string(camera_rect_.size().x);
406 height = std::to_string(camera_rect_.size().y);
407 }
408 else {
409 width = std::to_string(screen_rect_.size().x);
410 height = std::to_string(screen_rect_.size().y);
411 }
412
413 main_node.append_attribute("width").set_value((width + "px").c_str());
414 main_node.append_attribute("height").set_value((height + "px").c_str());
415 std::string viewbox = "0 0 " + width + " " + height;
416 main_node.append_attribute("viewBox").set_value(viewbox.c_str());
417
418 return main_node;
419}
420
421pugi::xml_node SVGExporter::write_animation_node(pugi::xml_node parent_node,
422 IndexMask frames,
423 const float duration)
424{
425 pugi::xml_node use_node = parent_node.append_child("use");
426 use_node.append_attribute("id").set_value("blender_animation");
427 std::string href_text = "#" + frame_name(frames.first());
428 use_node.append_attribute("href").set_value(href_text.c_str());
429
430 pugi::xml_node animate_node = use_node.append_child("animate");
431 animate_node.append_attribute("id").set_value("frame-by-frame_animation");
432 animate_node.append_attribute("attributeName").set_value("href");
433
434 std::string duration_text = std::to_string(duration) + "s";
435 animate_node.append_attribute("dur").set_value(duration_text.c_str());
436 animate_node.append_attribute("repeatCount").set_value("indefinite");
437
438 std::string animated_frame_ids = [&]() {
439 std::string frame_ids_text;
440 frames.foreach_index([&](const int frame) {
441 std::string frame_url_entry = "#" + frame_name(frame) + ";";
442 frame_ids_text.append(frame_url_entry);
443 });
444 return frame_ids_text;
445 }();
446
447 animate_node.append_attribute("values").set_value(animated_frame_ids.c_str());
448
449 return use_node;
450}
451
452pugi::xml_node SVGExporter::write_path(pugi::xml_node node,
453 const float4x4 &transform,
454 const Span<float3> positions,
455 const std::optional<Span<float3>> positions_left,
456 const std::optional<Span<float3>> positions_right,
457 const OffsetIndices<int> points_by_curve,
458 const Span<int> shape,
459 const VArray<bool> &cyclic,
460 const VArray<int8_t> &types,
461 const std::optional<float> width)
462{
463 pugi::xml_node element_node = node.append_child("path");
464
465 if (width) {
466 element_node.append_attribute("stroke-width").set_value(*width);
467 }
468
469 std::string txt;
470 for (const int curve_i : shape) {
471 txt.append("M");
472 const IndexRange points = points_by_curve[curve_i];
473
474 const Span<float3> curve_pos = positions.slice(points);
475
476 if (types[curve_i] != CURVE_TYPE_BEZIER || !positions_left || !positions_right) {
477 for (const int i : curve_pos.index_range()) {
478 const float2 screen_co = this->project_to_screen(transform, curve_pos[i]);
479
480 if (i > 0) {
481 txt.append("L");
482 }
483
484 txt.append(coord_to_svg_string(screen_co));
485 }
486 /* Close path (cyclic). */
487 if (cyclic[curve_i]) {
488 txt.append("z");
489 }
490 }
491 else {
492 const Span<float3> curve_pos_right = positions_right->slice(points);
493 const Span<float3> curve_pos_left = positions_left->slice(points);
494
495 for (const int i : curve_pos.index_range().drop_back(1)) {
496 const float2 screen_co = this->project_to_screen(transform, curve_pos[i]);
497 const float2 screen_co_right = this->project_to_screen(transform, curve_pos_right[i]);
498 const float2 screen_co_left = this->project_to_screen(transform, curve_pos_left[i + 1]);
499
500 txt.append(coord_to_svg_string(screen_co));
501 txt.append(" C ");
502 txt.append(coord_to_svg_string(screen_co_right));
503 txt.append(", ");
504 txt.append(coord_to_svg_string(screen_co_left));
505
506 if (i != curve_pos.size() - 2) {
507 txt.append(", ");
508 }
509 }
510
511 {
512 txt.append(", ");
513 const float2 screen_co = this->project_to_screen(transform, curve_pos.last());
514 txt.append(coord_to_svg_string(screen_co));
515 }
516
517 /* Close path (cyclic). */
518 if (cyclic[curve_i]) {
519 const float2 screen_co_right = this->project_to_screen(transform, curve_pos_right.last());
520 const float2 screen_co_left = this->project_to_screen(transform, curve_pos_left.first());
521 const float2 screen_co = this->project_to_screen(transform, curve_pos.first());
522
523 txt.append(" C ");
524 txt.append(coord_to_svg_string(screen_co_right));
525 txt.append(", ");
526 txt.append(coord_to_svg_string(screen_co_left));
527 txt.append(", ");
528 txt.append(coord_to_svg_string(screen_co));
529 txt.append("z");
530 }
531 }
532 }
533
534 element_node.append_attribute("d").set_value(txt.c_str());
535
536 return element_node;
537}
538
540{
541 bool result = true;
542 /* Support unicode character paths on Windows. */
543#ifdef WIN32
544 wchar_t *filepath_16 = alloc_utf16_from_8(filepath.c_str(), 0);
545 std::wstring wstr(filepath_16);
546 result = main_doc_.save_file(wstr.c_str());
547 free(filepath_16);
548#else
549 result = main_doc_.save_file(filepath.c_str());
550#endif
551
552 return result;
553}
554
556 const ExportParams &params,
557 Scene &scene,
558 StringRefNull filepath)
559{
560 SVGExporter exporter(context, params);
561 return exporter.export_scene(scene, filepath);
562}
563
564} // namespace blender::io::grease_pencil
Low-level operations for curves.
Low-level operations for grease pencil.
#define SNPRINTF_UTF8(dst, format,...)
#define MAX_ID_NAME
Definition DNA_ID.h:367
#define GP_STROKE_MITER_ANGLE_BEVEL
#define GP_STROKE_MITER_ANGLE_ROUND
Object is a sort of wrapper for general info.
#define BLI_assert_unreachable()
ChannelStorageType a
static IndexMask from_predicate(const IndexMask &universe, LinearAllocator<> &memory, Fn &&predicate, exec_mode::Mode mode=exec_mode::parallel)
constexpr IndexRange drop_back(int64_t n) const
constexpr IndexRange()=default
constexpr Span slice(int64_t start, int64_t size) const
Definition BLI_span.hh:141
constexpr const T & first() const
Definition BLI_span.hh:319
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr const T & last(const int64_t n=0) const
Definition BLI_span.hh:329
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
constexpr const char * c_str() const
bke::CurvesGeometry & strokes_for_write()
const bke::CurvesGeometry & strokes() const
void foreach_index(Fn &&fn, Mode mode=exec_mode::serial) const
GreasePencilExporter(const IOContext &context, const ExportParams &params)
std::string coord_to_svg_string(const float2 &screen_co) const
void foreach_shape_in_layer(const Object &object, const bke::greasepencil::Layer &layer, const bke::greasepencil::Drawing &drawing, WriteShapeFn shape_fn)
void prepare_render_params(Scene &scene, int frame_number)
bool is_selected_frame(const GreasePencil &grease_pencil, int frame_number) const
float2 project_to_screen(const float4x4 &transform, const float3 &position) const
GreasePencilExporter(const IOContext &context, const ExportParams &params)
void export_grease_pencil_layer(pugi::xml_node node, const Object &object, const bke::greasepencil::Layer &layer, const bke::greasepencil::Drawing &drawing)
void export_grease_pencil_objects(pugi::xml_node node, int frame_number)
pugi::xml_node write_path(pugi::xml_node node, const float4x4 &transform, const Span< float3 > positions, const std::optional< Span< float3 > > positions_left, const std::optional< Span< float3 > > positions_right, const OffsetIndices< int > points_by_curve, const Span< int > shape, const VArray< bool > &cyclic, const VArray< int8_t > &types, std::optional< float > width)
pugi::xml_node write_animation_node(pugi::xml_node parent_node, IndexMask frames, float duration)
ExportStatus export_scene(Scene &scene, StringRefNull filepath)
CCL_NAMESPACE_BEGIN struct Options options
#define layer
void free(Subdiv *subdiv)
Definition subdiv.cc:192
bke::CurvesGeometry convert_curves(const bke::CurvesGeometry &src_curves, const IndexMask &selection, CurveType dst_type, const bke::AttributeFilter &attribute_filter, const ConvertCurvesOptions &options={})
static std::string rgb_to_hexstr(const float color[3])
static void write_fill_color_attribute(pugi::xml_node node, const ColorGeometry4f &fill_color, const float layer_opacity)
static void write_stroke_color_attribute(pugi::xml_node node, const ColorGeometry4f &stroke_color, const float stroke_opacity, const std::optional< float > miter_limit_angle, const bool round_cap)
static void write_rect(pugi::xml_node node, const float x, const float y, const float width, const float height, const float thickness, const std::string &hexcolor)
ExportStatus export_svg(const IOContext &context, const ExportParams &params, Scene &scene, StringRefNull filepath)
static std::string frame_name(int frame_number)
constexpr const char * svg_exporter_version
T sin(const AngleRadianBase< T > &a)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
void BKE_scene_graph_update_for_newframe(Depsgraph *depsgraph)
Definition scene.cc:2953
unsigned __int64 uint64_t
Definition BKE_text.h:91
void linearrgb_to_srgb_v3_v3(float srgb[3], const float linear[3])
MatBase< float, 4, 4 > float4x4
MINLINE void rgb_float_to_uchar(unsigned char r_col[3], const float col_f[3])
VecBase< float, 2 > float2
unsigned char uchar
Definition BKE_text.h:58
T * DEG_get_evaluated(const Depsgraph *depsgraph, T *id)
bool BKE_scene_camera_switch_update(Scene *scene)
Definition scene.cc:2480
ColorSceneLinear4f< eAlpha::Premultiplied > ColorGeometry4f
char name[258]
Definition DNA_ID.h:433
struct RenderData r
wchar_t * alloc_utf16_from_8(const char *in8, size_t add)
Definition utfconv.cc:294