Debian Codegraph @

tests/svg_element.cpp

raw
1 #include <algorithm>
2 #include <cassert>
3 #include <cmath>
4 #include <format>
5 #include <limits>
6 #include <stdexcept>
7
8 #include "svg_element.h"
9 #include <util/unreachable.h>
10
11 SVG::SVGElement::SVGElement(SVGElementType etype) : elem_type(etype) {}
12
13 static double px_to_pt(double px) {
14 // a `pt` is 0.75 `px`. See e.g.
15 // https://oreillymedia.github.io/Using_SVG/guide/units.html
16 return px * 3 / 4;
17 }
18
19 bool SVG::SVGElement::is_closed_shape_element() const {
20 switch (elem_type) {
21 case SVG::SVGElementType::Circle:
22 case SVG::SVGElementType::Ellipse:
23 case SVG::SVGElementType::Polygon:
24 case SVG::SVGElementType::Rect:
25 return true;
26 default:
27 return false;
28 }
29 }
30
31 bool SVG::SVGElement::is_shape_element() const {
32 switch (elem_type) {
33 case SVG::SVGElementType::Circle:
34 case SVG::SVGElementType::Ellipse:
35 case SVG::SVGElementType::Line:
36 case SVG::SVGElementType::Path:
37 case SVG::SVGElementType::Polygon:
38 case SVG::SVGElementType::Polyline:
39 case SVG::SVGElementType::Rect:
40 return true;
41 default:
42 return false;
43 }
44 }
45
46 static std::string xml_encode(const std::string &text) {
47 std::string out;
48 for (const char &ch : text) {
49 switch (ch) {
50 case '>':
51 out += "&gt;";
52 break;
53 case '<':
54 out += "&lt;";
55 break;
56 case '-':
57 out += "&#45;";
58 break;
59 case '&':
60 out += "&amp;";
61 break;
62 default:
63 out += ch;
64 }
65 }
66 return out;
67 }
68
69 static std::string rgb_to_hex(const std::string &color, double opacity = 1.0) {
70 const auto comma1 = color.find_first_of(",");
71 const auto r = std::stoi(color.substr(4, comma1 - 1));
72 const auto comma2 = color.find_first_of(",", comma1 + 1);
73 const auto g = std::stoi(color.substr(comma1 + 1, comma2 - 1));
74 const auto close_par = color.find_first_of(")", comma2 + 1);
75 const auto b = std::stoi(color.substr(comma2 + 1, close_par - 1));
76 const auto opacity_int = std::lround(opacity * 255.0);
77 const auto opacity_hex_str =
78 opacity_int < 255 ? std::format("{:02x}", opacity_int) : "";
79 return std::format("#{:02x}{:02x}{:02x}{}", r, g, b, opacity_hex_str);
80 }
81
82 // convert a valid color specification to the flavor that Graphviz uses in the
83 // SVG
84 static std::string to_graphviz_color(const std::string &color) {
85 if (color == "rgb(0,0,0)") {
86 return "black";
87 } else if (color == "rgb(255,255,255)") {
88 return "white";
89 } else if (color.starts_with("rgb")) {
90 return rgb_to_hex(color);
91 } else {
92 return color;
93 }
94 }
95
96 // convert a valid color specification to the RGB or RGBA type that Graphviz
97 // uses in the DOT source
98 std::string SVG::to_dot_color(const std::string &color, double opacity) {
99 if (color == "none") {
100 return "#00000000";
101 }
102 if (opacity < 1.0) {
103 if (!color.starts_with("rgb")) {
104 throw std::runtime_error{std::format(
105 "Cannot convert stroke={}, stroke_opacity={} to Graphviz color",
106 color, opacity)};
107 }
108 }
109 return rgb_to_hex(color, opacity);
110 }
111
112 void SVG::SVGElement::add_bbox() {
113 const auto bbox = SVGElement::bbox();
114 add_rect(bbox, "green");
115 }
116
117 void SVG::SVGElement::add_rect(SVGRect rect, const std::string color) {
118 SVG::SVGElement element{SVG::SVGElementType::Rect};
119 element.attributes.x = rect.x;
120 element.attributes.y = rect.y;
121 element.attributes.width = rect.width;
122 element.attributes.height = rect.height;
123 element.attributes.stroke_width = 0.1;
124 element.attributes.stroke = color;
125 element.attributes.fill = "none";
126 children.push_back(element);
127 }
128
129 void SVG::SVGElement::add_outline_bbox() {
130 const auto bbox = SVGElement::outline_bbox();
131 add_rect(bbox, "blue");
132 }
133
134 void SVG::SVGElement::add_outline_overlap_bbox(SVG::SVGElement other,
135 const double tolerance) {
136 const auto bbox = outline_bbox();
137 const auto other_bbox = other.outline_bbox();
138 const auto overlap_bbox = bbox.intersection(other_bbox);
139 if (overlap_bbox.width <= 0 || overlap_bbox.height <= 0) {
140 return;
141 }
142 const auto within_tolerance =
143 overlap_bbox.width <= tolerance && overlap_bbox.height <= tolerance;
144 const auto color = within_tolerance ? "yellow" : "red";
145 add_rect(overlap_bbox, color);
146 }
147
148 SVG::SVGRect SVG::SVGElement::bbox(bool throw_if_bbox_not_defined) {
149 if (!m_bbox.has_value()) {
150 // negative width and height bbox that will be immediately replaced by the
151 // first bbox found
152 m_bbox = {.x = std::numeric_limits<double>::max() / 2,
153 .y = std::numeric_limits<double>::max() / 2,
154 .width = std::numeric_limits<double>::lowest(),
155 .height = std::numeric_limits<double>::lowest()};
156 switch (elem_type) {
157 case SVG::SVGElementType::Group:
158 // SVG group bounding box is determined solely by its children
159 break;
160 case SVG::SVGElementType::Ellipse: {
161 m_bbox = {
162 .x = attributes.cx - attributes.rx,
163 .y = attributes.cy - attributes.ry,
164 .width = attributes.rx * 2,
165 .height = attributes.ry * 2,
166 };
167 break;
168 }
169 case SVG::SVGElementType::Polygon:
170 case SVG::SVGElementType::Polyline: {
171 for (const auto &point : attributes.points) {
172 m_bbox->extend(point);
173 }
174 break;
175 }
176 case SVG::SVGElementType::Path: {
177 if (path_points.empty()) {
178 throw std::runtime_error{"No points for 'path' element"};
179 }
180 for (const auto &point : path_points) {
181 m_bbox->extend(point);
182 }
183 break;
184 }
185 case SVG::SVGElementType::Rect: {
186 m_bbox = {
187 .x = attributes.x,
188 .y = attributes.y,
189 .width = attributes.width,
190 .height = attributes.height,
191 };
192 break;
193 }
194 case SVG::SVGElementType::Text: {
195 m_bbox = text_bbox();
196 break;
197 }
198 case SVG::SVGElementType::Title:
199 // title has no size
200 if (throw_if_bbox_not_defined) {
201 throw std::runtime_error{"A 'title' element has no bounding box"};
202 }
203 break;
204 default:
205 throw std::runtime_error{
206 std::format("Unhandled svg element type {}", tag(elem_type))};
207 }
208
209 const auto throw_if_child_bbox_is_not_defined = false;
210 for (auto &child : children) {
211 const auto child_bbox = child.bbox(throw_if_child_bbox_is_not_defined);
212 m_bbox->extend(child_bbox);
213 }
214 }
215
216 return *m_bbox;
217 }
218
219 SVG::SVGRect SVG::SVGElement::outline_bbox(bool throw_if_bbox_not_defined) {
220 if (m_outline_bbox.has_value()) {
221 return *m_outline_bbox;
222 }
223 // negative width and height bbox that will be immediately replaced by the
224 // first bbox found
225 m_bbox = {.x = std::numeric_limits<double>::max() / 2,
226 .y = std::numeric_limits<double>::max() / 2,
227 .width = std::numeric_limits<double>::lowest(),
228 .height = std::numeric_limits<double>::lowest()};
229 switch (elem_type) {
230 case SVG::SVGElementType::Group:
231 // SVG group bounding box is determined solely by its children
232 break;
233 case SVG::SVGElementType::Ellipse: {
234 const auto stroke_width = (attributes.rx == 0 && attributes.ry == 0)
235 ? 0
236 : attributes.stroke_width;
237 m_bbox = {
238 .x = attributes.cx - attributes.rx - stroke_width / 2,
239 .y = attributes.cy - attributes.ry - stroke_width / 2,
240 .width = attributes.rx * 2 + stroke_width,
241 .height = attributes.ry * 2 + stroke_width,
242 };
243 break;
244 }
245 case SVG::SVGElementType::Polygon: {
246 // it takes at least 3 points to make a polygon (triangle) and Graphviz
247 // always generates the last point to be the same as the first so there
248 // will always be at least 4 points
249 const auto &points = attributes.points;
250 if (points.size() < 4) {
251 throw std::runtime_error{"Too few points"};
252 }
253 if (points.front().x != points.back().x ||
254 points.front().y != points.back().y) {
255 throw std::runtime_error{"First and last point are not the same"};
256 }
257 if (has_all_points_equal()) {
258 // the polygon has no size and will not be visible, so just arbitrarily
259 // select one of its (equal) points as its outline bounding box
260 const auto first_point = points.at(0);
261 m_bbox->extend(first_point);
262 break;
263 }
264 const auto clockwise = has_clockwise_points();
265 // the first and last points are always the same so we skip the last
266 for (auto it = points.cbegin(); it != points.cend() - 1; ++it) {
267 const SVG::SVGPoint &prev_point = [&]() {
268 if (it == points.begin()) {
269 // the last point is the same as the first so we must use the next
270 // to last one as the next point to get the start point of the
271 // current path segment
272 return *(points.cend() - 2);
273 } else {
274 return *std::prev(it);
275 }
276 }();
277 const auto &point = *it;
278 // there is always a next point since we iterate only to the next to
279 // last point
280 const auto &next_point = *std::next(it);
281 const SVG::SVGPoints miter_shape =
282 clockwise ?
283 // Graphviz draws some polygons clockwise and some
284 // counter-clockwise.
285 SVGElement::miter_shape(prev_point, point, next_point)
286 :
287 // the SVG spec assumes clockwise so we swap the points
288 SVGElement::miter_shape(next_point, point, prev_point);
289 for (const auto &p : miter_shape) {
290 m_bbox->extend(p);
291 }
292 }
293 break;
294 }
295 case SVG::SVGElementType::Path: {
296 if (path_points.empty()) {
297 throw std::runtime_error{"No points for 'path' element"};
298 }
299 const auto first_point = path_points.front();
300 auto is_vertical = std::all_of(
301 path_points.cbegin(), path_points.cend(),
302 [&](const SVGPoint &point) { return point.x == first_point.x; });
303 auto is_horizontal = std::all_of(
304 path_points.cbegin(), path_points.cend(),
305 [&](const SVGPoint &point) { return point.y == first_point.y; });
306 if (!is_vertical && !is_horizontal) {
307 const std::size_t num_points_in_cylinder_node_shape_path1 = 19;
308 const std::size_t num_points_in_cylinder_node_shape_path2 = 7;
309 if (path_points.size() == num_points_in_cylinder_node_shape_path1 ||
310 path_points.size() == num_points_in_cylinder_node_shape_path2) {
311 // cylinder node shape which is flat at the extreme points so we can
312 // just extend the crossing points with penwidth / 2 and exclude the
313 // intermediate control points. Graphviz uses cubic splines so there are
314 // always two intermediate control points between the curve segment
315 // endpoints.
316 const auto num_intermediate_control_points = 2;
317 for (std::size_t i = 0; i < path_points.size();
318 i += num_intermediate_control_points + 1) {
319 const auto &point = path_points[i];
320 SVG::SVGRect point_bbox = {
321 .x = point.x - attributes.stroke_width / 2,
322 .y = point.y - attributes.stroke_width / 2,
323 .width = attributes.stroke_width,
324 .height = attributes.stroke_width,
325 };
326 m_bbox->extend(point_bbox);
327 }
328 break;
329 }
330 const std::size_t num_points_in_curve_arrow_shape_path = 4;
331 if (path_points.size() == num_points_in_curve_arrow_shape_path) {
332 const auto horizontal_start = path_points[0].x;
333 const auto horizontal_control1 = path_points[1].x;
334 const auto horizontal_control2 = path_points[2].x;
335 const auto horizontal_end = path_points[3].x;
336
337 const auto vertical_start = path_points[0].y;
338 const auto vertical_control1 = path_points[1].y;
339 const auto vertical_control2 = path_points[2].y;
340 const auto vertical_end = path_points[3].y;
341
342 const auto has_horizontally_symmetric_control_points =
343 horizontal_start - horizontal_control1 ==
344 horizontal_control2 - horizontal_end;
345
346 const auto has_vertically_symmetric_control_points =
347 vertical_start - vertical_control1 ==
348 vertical_control2 - vertical_end;
349
350 const auto is_horizontally_mirrored =
351 horizontal_start == horizontal_end &&
352 horizontal_control1 == horizontal_control2 &&
353 has_vertically_symmetric_control_points;
354
355 const auto is_vertically_mirrored =
356 vertical_start == vertical_end &&
357 vertical_control1 == vertical_control2 &&
358 has_horizontally_symmetric_control_points;
359
360 if (is_horizontally_mirrored || is_vertically_mirrored) {
361 // A bezier curve which is either vertically or horizontally mirrored
362 // is flat at the center and has a negligible extension "backwards" at
363 // the start and end points. The Graphviz arrow shape `curve`, which
364 // is a cubic Bezier approximation of a semicircle, is a special case
365 // of this. A vertical edge with a `curve` arrow head is vertically
366 // mirrored and a horizontal edge with a `curve` arrow head is
367 // horizontally mirrored.
368 {
369 const auto horizontal_endpoint_extension =
370 is_vertically_mirrored ? attributes.stroke_width / 2 : 0;
371 const auto vertical_endpoint_extension =
372 is_horizontally_mirrored ? attributes.stroke_width / 2 : 0;
373 const auto num_intermediate_control_points = 2;
374 for (std::size_t i = 0; i < path_points.size();
375 i += num_intermediate_control_points + 1) {
376 const auto &point = path_points[i];
377 const SVG::SVGRect point_bbox = {
378 .x = point.x - horizontal_endpoint_extension,
379 .y = point.y - vertical_endpoint_extension,
380 .width = horizontal_endpoint_extension * 2,
381 .height = vertical_endpoint_extension * 2,
382 };
383 m_bbox->extend(point_bbox);
384 }
385 const SVGPoint midpoint = cubic_bezier(0.5);
386 const SVG::SVGRect point_bbox = {
387 .x = midpoint.x - attributes.stroke_width / 2,
388 .y = midpoint.y - attributes.stroke_width / 2,
389 .width = attributes.stroke_width,
390 .height = attributes.stroke_width,
391 };
392 m_bbox->extend(point_bbox);
393 }
394 break;
395 }
396 const auto xmin = std::min(horizontal_start, horizontal_end);
397 const auto xmax = std::max(horizontal_start, horizontal_end);
398 const auto ymin = std::min(vertical_start, vertical_end);
399 const auto ymax = std::max(vertical_start, vertical_end);
400 if (horizontal_control1 >= xmin && horizontal_control1 <= xmax &&
401 horizontal_control2 >= xmin && horizontal_control2 <= xmax &&
402 vertical_control1 >= ymin && vertical_control1 <= ymax &&
403 vertical_control2 >= ymin && vertical_control2 <= ymax) {
404 // the control points are within a bounding box defined by the start
405 // and end points. This means that the Bezier curve is completely
406 // contained within this box, except for the extension caused by the
407 // stroke width. This extension can be calculated using the angle at
408 // the start and end points which is given by the closest control
409 // point. The Graphviz arrow shapes `rcurve`, `lcurve`, `ricurve` and
410 // `licurve` fulfills this condition.
411 const auto start_dx = horizontal_start - horizontal_control1;
412 const auto start_dy = vertical_start - vertical_control1;
413 const auto start_hypot = std::hypot(start_dx, start_dy);
414 const auto start_cos = start_dx / start_hypot;
415 const auto start_sin = start_dy / start_hypot;
416 const SVG::SVGPoint start_extension_left = {
417 horizontal_start + attributes.stroke_width / 2 * start_sin,
418 vertical_start - attributes.stroke_width / 2 * start_cos};
419 const SVG::SVGPoint start_extension_right = {
420 horizontal_start - attributes.stroke_width / 2 * start_sin,
421 vertical_start + attributes.stroke_width / 2 * start_cos};
422 m_bbox->extend(start_extension_left);
423 m_bbox->extend(start_extension_right);
424 const auto end_dx = horizontal_end - horizontal_control2;
425 const auto end_dy = vertical_end - vertical_control2;
426 const auto end_hypot = std::hypot(end_dx, end_dy);
427 const auto end_cos = end_dx / end_hypot;
428 const auto end_sin = end_dy / end_hypot;
429 const SVG::SVGPoint end_extension_left = {
430 horizontal_end + attributes.stroke_width / 2 * end_sin,
431 vertical_end + -attributes.stroke_width / 2 * end_cos};
432 const SVG::SVGPoint end_extension_right = {
433 horizontal_end + -attributes.stroke_width / 2 * end_sin,
434 vertical_end + attributes.stroke_width / 2 * end_cos};
435 m_bbox->extend(end_extension_left);
436 m_bbox->extend(end_extension_right);
437 break;
438 }
439 }
440 throw std::runtime_error(
441 "paths other than straight vertical, straight horizontal or the "
442 "cylinder special case are currently not supported");
443 }
444 // we now know we have a straight horizontal or vertical line (or the
445 // degenerate case of a point)
446 if (is_vertical) {
447 const SVG::SVGRect first_point_bbox = {
448 first_point.x - attributes.stroke_width / 2, first_point.y,
449 attributes.stroke_width, 0};
450 m_bbox->extend(first_point_bbox);
451 for (const auto &point : path_points) {
452 m_bbox->extend(point);
453 }
454 }
455 if (is_horizontal) {
456 for (const auto &point : path_points) {
457 m_bbox->extend(point);
458 }
459 const SVG::SVGRect first_point_bbox = {
460 first_point.x, first_point.y - attributes.stroke_width / 2, 0,
461 attributes.stroke_width};
462 m_bbox->extend(first_point_bbox);
463 }
464 break;
465 }
466 case SVG::SVGElementType::Polyline: {
467 const auto &points = attributes.points;
468 if (points.size() < 2) {
469 throw std::runtime_error{"Too few points for 'polyline' element"};
470 }
471
472 // handle first point which may not be part of a corner
473 {
474 const auto first_point = points.front();
475 const auto next_point = points[1];
476 const auto dx = first_point.x - next_point.x;
477 const auto dy = first_point.y - next_point.y;
478 const auto hypot = std::hypot(dx, dy);
479 const auto cosAlpha = dx / hypot;
480 const auto sinAlpha = dy / hypot;
481 // a polyline extends with half the stroke width in both perpendicular
482 // directions, but not along the line at its endpoints
483 const auto x_extension = std::abs(attributes.stroke_width / 2 * sinAlpha);
484 const auto y_extension = std::abs(attributes.stroke_width / 2 * cosAlpha);
485 const SVG::SVGRect first_point_bbox = {points.front().x - x_extension,
486 points.front().y - y_extension,
487 x_extension * 2, y_extension * 2};
488 m_bbox->extend(first_point_bbox);
489 }
490
491 // handle last point which may not be part of a corner
492 {
493 const auto last_point = points.back();
494 const auto prev_point = *(points.cend() - 2);
495 const auto dx = last_point.x - prev_point.x;
496 const auto dy = last_point.y - prev_point.y;
497 const auto hypot = std::hypot(dx, dy);
498 const auto cosAlpha = dx / hypot;
499 const auto sinAlpha = dy / hypot;
500 // a polyline extends with half the stroke width in both perpendicular
501 // directions, but not along the line at its endpoints
502 const auto x_extension = std::abs(attributes.stroke_width / 2 * sinAlpha);
503 const auto y_extension = std::abs(attributes.stroke_width / 2 * cosAlpha);
504 const SVG::SVGRect last_point_bbox = {points.back().x - x_extension,
505 points.back().y - y_extension,
506 x_extension * 2, y_extension * 2};
507 m_bbox->extend(last_point_bbox);
508 }
509
510 if (points.size() >= 3) {
511 // at least one corner
512 if (has_all_points_equal()) {
513 // the polyline has no size and will not be visible, so just arbitrarily
514 // select one of its (equal) points as its outline bounding box
515 const auto first_point = points.at(0);
516 m_bbox->extend(first_point);
517 break;
518 }
519
520 const auto clockwise = has_clockwise_points();
521 for (auto it = points.cbegin() + 1; it < points.cend() - 1; ++it) {
522 // there is always a previous point since we iterate from the second
523 // point
524 const auto &prev_point = *std::prev(it);
525 const auto &point = *it;
526 // there is always a next point since we iterate only to the next to
527 // last point
528 const auto &next_point = *std::next(it);
529 SVG::SVGPoints miter_shape =
530 // Graphviz draws some polylines clockwise and some
531 // counter-clockwise.
532 clockwise ? SVGElement::miter_shape(prev_point, point, next_point) :
533 // `miter_point` assumes clockwise so we swap the points
534 SVGElement::miter_shape(next_point, point, prev_point);
535 for (const auto &p : miter_shape) {
536 m_bbox->extend(p);
537 }
538 }
539 }
540 break;
541 }
542 case SVG::SVGElementType::Rect:
543 m_bbox = {
544 .x = attributes.x - attributes.stroke_width / 2,
545 .y = attributes.y - attributes.stroke_width / 2,
546 .width = attributes.width + attributes.stroke_width,
547 .height = attributes.height + attributes.stroke_width,
548 };
549 break;
550 case SVG::SVGElementType::Text:
551 m_bbox = text_bbox();
552 break;
553 case SVG::SVGElementType::Title:
554 // title has no size
555 if (throw_if_bbox_not_defined) {
556 throw std::runtime_error{"A 'title' element has no bounding box"};
557 }
558 break;
559 default:
560 throw std::runtime_error{
561 std::format("Unhandled svg element type {}", tag(elem_type))};
562 }
563
564 const auto throw_if_child_bbox_is_not_defined = false;
565 for (auto &child : children) {
566 const auto child_bbox =
567 child.outline_bbox(throw_if_child_bbox_is_not_defined);
568 m_bbox->extend(child_bbox);
569 }
570
571 return *m_bbox;
572 }
573
574 SVG::SVGElement &SVG::SVGElement::find_child(const SVG::SVGElementType etype,
575 std::size_t index) {
576 std::size_t i = 0;
577 for (auto &child : children) {
578 if (child.elem_type == etype) {
579 if (i == index) {
580 return child;
581 }
582 ++i;
583 }
584 }
585 throw std::runtime_error(
586 std::format("SVG element only has {} \"{}\" children, index {} not found",
587 i, tag(etype), index));
588 }
589
590 SVG::SVGRect SVG::SVGElement::text_bbox() const {
591 assert(elem_type == SVG::SVGElementType::Text && "Not a 'text' element");
592
593 if (attributes.font_family != "Courier,monospace") {
594 throw std::runtime_error(
595 std::format("Cannot calculate bounding box for font \"{}\"",
596 attributes.font_family));
597 }
598
599 // Empirically determined font metrics for the Courier font
600 const auto courier_width_per_pt = 0.6;
601 const auto courier_height_per_pt = 1.2;
602 const auto descent_per_pt = 0.257;
603 const auto font_width = attributes.font_size * courier_width_per_pt;
604 const auto font_height = attributes.font_size * courier_height_per_pt;
605 const auto descent = attributes.font_size * descent_per_pt;
606
607 const SVG::SVGRect bbox = {
608 .x = attributes.x - font_width * text.size() / 2,
609 .y = attributes.y - font_height + descent,
610 .width = font_width * text.size(),
611 .height = font_height,
612 };
613 return bbox;
614 }
615
616 void SVG::SVGElement::append_attribute(std::string &output,
617 const std::string &attribute) const {
618 if (attribute.empty()) {
619 return;
620 }
621 if (!output.empty()) {
622 output += " ";
623 }
624 output += attribute;
625 }
626
627 static double interpolate(double y0, double y1, double x) {
628 double dy = y1 - y0;
629
630 return y0 + x * dy;
631 }
632
633 // The cubic Bezier implementation is taken from
634 // https://stackoverflow.com/a/37642695/3122101
635 SVG::SVGPoint SVG::SVGElement::cubic_bezier(double t) {
636 assert(t >= 0);
637 assert(t <= 1);
638 assert(path_points.size() == 4);
639
640 const auto x0 = path_points[0].x;
641 const auto y0 = path_points[0].y;
642 const auto x1 = path_points[1].x;
643 const auto y1 = path_points[1].y;
644 const auto x2 = path_points[2].x;
645 const auto y2 = path_points[2].y;
646 const auto x3 = path_points[3].x;
647 const auto y3 = path_points[3].y;
648
649 const auto xa = interpolate(x0, x1, t);
650 const auto ya = interpolate(y0, y1, t);
651 const auto xb = interpolate(x1, x2, t);
652 const auto yb = interpolate(y1, y2, t);
653 const auto xc = interpolate(x2, x3, t);
654 const auto yc = interpolate(y2, y3, t);
655
656 const auto xm = interpolate(xa, xb, t);
657 const auto ym = interpolate(ya, yb, t);
658 const auto xn = interpolate(xb, xc, t);
659 const auto yn = interpolate(yb, yc, t);
660
661 const auto x = interpolate(xm, xn, t);
662 const auto y = interpolate(ym, yn, t);
663
664 return {x, y};
665 }
666
667 bool SVG::SVGElement::has_all_points_equal() const {
668 assert((elem_type == SVG::SVGElementType::Polygon ||
669 elem_type == SVG::SVGElementType::Polyline) &&
670 "not a polygon or polyline");
671 const auto points = attributes.points;
672 assert(!points.empty() > 0 && "no points");
673 return std::equal(points.begin() + 1, points.end(), points.begin());
674 }
675
676 bool SVG::SVGElement::has_clockwise_points() const {
677 assert((elem_type == SVG::SVGElementType::Polygon ||
678 elem_type == SVG::SVGElementType::Polyline) &&
679 "not a polygon or polyline");
680 assert(attributes.points.size() >= 3 && "too few points");
681 // Sum over the edges, (x2 − x1)(y2 + y1). If the result is positive, the
682 // curve is clockwise, if it's negative the curve is counter-clockwise.
683 // Implementation is based on https://stackoverflow.com/a/1165943/3122101
684 const auto &points = attributes.points;
685 double sum = 0;
686 for (auto it = points.cbegin(); it < points.cend() - 1; ++it) {
687 const auto &[x1, y1i] = *it;
688 const auto &[x2, y2i] = *std::next(it);
689 // SVG uses inverted y axis, so negate y values
690 const auto y1 = -y1i;
691 const auto y2 = -y2i;
692 sum += (x2 - x1) * (y2 + y1);
693 }
694 return sum > 0;
695 }
696
697 std::string SVG::SVGElement::fill_attribute_to_string() const {
698 if (attributes.fill.empty()) {
699 return "";
700 }
701
702 return std::format(R"(fill="{}")", to_graphviz_color(attributes.fill));
703 }
704
705 std::string SVG::SVGElement::id_attribute_to_string() const {
706 if (attributes.id.empty()) {
707 return "";
708 }
709
710 return std::format(R"(id="{}")", attributes.id);
711 }
712
713 std::string SVG::SVGElement::fill_opacity_attribute_to_string() const {
714 if (attributes.fill_opacity == 1) {
715 // Graphviz doesn't set `fill-opacity` to 1 since that's the default
716 return "";
717 }
718
719 if (attributes.fill_opacity == 0) {
720 // Graphviz doesn't set `fill-opacity` to 0 since in that case it sets
721 // `fill` to "none" instead
722 return "";
723 }
724
725 return std::format(R"(fill-opacity="{}")", attributes.fill_opacity);
726 }
727
728 std::string SVG::SVGElement::points_attribute_to_string() const {
729 std::string points_attribute_str = R"|(points=")|";
730 const char *separator = "";
731 for (const auto &point : attributes.points) {
732 points_attribute_str += separator + std::format("{},{}", point.x, point.y);
733 separator = " ";
734 }
735 points_attribute_str += '"';
736
737 return points_attribute_str;
738 }
739
740 std::string SVG::SVGElement::stroke_attribute_to_string() const {
741 if (attributes.stroke.empty()) {
742 return "";
743 }
744
745 return std::format(R"(stroke="{}")",
746 stroke_to_graphviz_color(attributes.stroke));
747 }
748
749 std::string SVG::SVGElement::stroke_opacity_attribute_to_string() const {
750 if (attributes.stroke_opacity == 1) {
751 // Graphviz doesn't set `stroke-opacity` to 1 since that's the default
752 return "";
753 }
754
755 if (attributes.stroke_opacity == 0) {
756 // Graphviz doesn't set `stroke-opacity` to 0 since in that case it sets
757 // `stroke` to "none" instead
758 return "";
759 }
760
761 return std::format(R"(stroke-opacity="{}")", attributes.stroke_opacity);
762 }
763
764 std::string SVG::SVGElement::stroke_width_attribute_to_string() const {
765 if (attributes.stroke_width == 1) {
766 // Graphviz doesn't set `stroke-width` to 1 since that's the default
767 return "";
768 }
769
770 return std::format(R"(stroke-width="{}")", attributes.stroke_width);
771 }
772
773 std::string SVG::SVGElement::to_string(std::size_t indent_size = 2) const {
774 std::string output;
775 output += R"(<?xml version="1.0" encoding="UTF-8" standalone="no"?>)"
776 "\n";
777 output += R"(<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN")"
778 "\n";
779 output += R"( "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">)"
780 "\n";
781 output += std::format("<!-- Generated by graphviz version {} "
782 "({})\n -->\n",
783 graphviz_version, graphviz_build_date);
784 to_string_impl(output, indent_size, 0);
785 return output;
786 }
787
788 void SVG::SVGElement::to_string_impl(std::string &output,
789 std::size_t indent_size,
790 std::size_t current_indent) const {
791 const auto indent_str = std::string(current_indent, ' ');
792 output += indent_str;
793
794 if (elem_type == SVG::SVGElementType::Svg) {
795 const auto comment = std::format("Title: {} Pages: 1", graphviz_id);
796 output += std::format("<!-- {} -->\n", xml_encode(comment));
797 }
798 if (elem_type == SVG::SVGElementType::Group &&
799 (attributes.class_ == "node" || attributes.class_ == "edge")) {
800 const auto comment = graphviz_id;
801 output += std::format("<!-- {} -->\n", xml_encode(comment));
802 }
803
804 output += "<";
805 output += tag(elem_type);
806
807 std::string attributes_str{};
808 append_attribute(attributes_str, id_attribute_to_string());
809 switch (elem_type) {
810 case SVG::SVGElementType::Ellipse:
811 append_attribute(attributes_str, fill_attribute_to_string());
812 append_attribute(attributes_str, fill_opacity_attribute_to_string());
813 append_attribute(attributes_str, stroke_attribute_to_string());
814 append_attribute(attributes_str, stroke_width_attribute_to_string());
815 append_attribute(attributes_str, stroke_opacity_attribute_to_string());
816 attributes_str +=
817 std::format(R"( cx="{}" cy="{}" rx="{}" ry="{}")", attributes.cx,
818 attributes.cy, attributes.rx, attributes.ry);
819 break;
820 case SVG::SVGElementType::Group:
821 attributes_str += std::format(R"( class="{}")", attributes.class_);
822 if (attributes.transform.has_value()) {
823 const auto transform = attributes.transform;
824 attributes_str += std::format(
825 R"|( transform="scale({} {}) rotate({}) translate({} {})")|",
826 transform->a, transform->d, transform->c, transform->e, transform->f);
827 }
828 break;
829 case SVG::SVGElementType::Path: {
830 append_attribute(attributes_str, fill_attribute_to_string());
831 append_attribute(attributes_str, fill_opacity_attribute_to_string());
832 append_attribute(attributes_str, stroke_attribute_to_string());
833 append_attribute(attributes_str, stroke_width_attribute_to_string());
834 append_attribute(attributes_str, stroke_opacity_attribute_to_string());
835 attributes_str += R"|( d=")|";
836 auto command = 'M';
837 for (const auto &point : path_points) {
838 attributes_str += std::format("{}{},{}", command, point.x, point.y);
839 switch (command) {
840 case 'M':
841 command = 'C';
842 break;
843 case 'C':
844 command = ' ';
845 break;
846 case ' ':
847 break;
848 default:
849 UNREACHABLE();
850 }
851 }
852 attributes_str += '"';
853 break;
854 }
855 case SVG::SVGElementType::Polygon:
856 append_attribute(attributes_str, fill_attribute_to_string());
857 append_attribute(attributes_str, fill_opacity_attribute_to_string());
858 append_attribute(attributes_str, stroke_attribute_to_string());
859 append_attribute(attributes_str, stroke_width_attribute_to_string());
860 append_attribute(attributes_str, stroke_opacity_attribute_to_string());
861 append_attribute(attributes_str, points_attribute_to_string());
862 break;
863 case SVG::SVGElementType::Polyline:
864 append_attribute(attributes_str, fill_attribute_to_string());
865 append_attribute(attributes_str, stroke_attribute_to_string());
866 append_attribute(attributes_str, stroke_width_attribute_to_string());
867 append_attribute(attributes_str, stroke_opacity_attribute_to_string());
868 append_attribute(attributes_str, points_attribute_to_string());
869 break;
870 case SVG::SVGElementType::Rect:
871 attributes_str +=
872 std::format(R"(x="{}" y="{}" width="{}" height="{}")", attributes.x,
873 attributes.y, attributes.width, attributes.height);
874 append_attribute(attributes_str, fill_attribute_to_string());
875 append_attribute(attributes_str, stroke_attribute_to_string());
876 append_attribute(attributes_str, stroke_width_attribute_to_string());
877 append_attribute(attributes_str, stroke_opacity_attribute_to_string());
878 break;
879 case SVG::SVGElementType::Svg:
880 attributes_str += std::format(
881 R"(width="{}pt" height="{}pt")"
882 "\n"
883 R"( viewBox="{:.2f} {:.2f} {:.2f} {:.2f}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink")",
884 std::lround(px_to_pt(attributes.width)),
885 std::lround(px_to_pt(attributes.height)), attributes.viewBox.x,
886 attributes.viewBox.y, attributes.viewBox.width,
887 attributes.viewBox.height);
888 break;
889 case SVG::SVGElementType::Text:
890 attributes_str += std::format(
891 R"(xml:space="preserve" text-anchor="{}" x="{}" y="{}" font-family="{}" font-size="{:.2f}")",
892 attributes.text_anchor, attributes.x, attributes.y,
893 attributes.font_family, attributes.font_size);
894 break;
895 case SVG::SVGElementType::Title:
896 // Graphviz doesn't generate attributes on 'title' elements
897 break;
898 default:
899 throw std::runtime_error{std::format(
900 "Attributes on '{}' elements are not yet implemented", tag(elem_type))};
901 }
902 if (!attributes_str.empty()) {
903 output += " ";
904 }
905 output += attributes_str;
906
907 if (children.empty() && text.empty()) {
908 output += "/>\n";
909 } else {
910 output += ">";
911 if (!text.empty()) {
912 output += xml_encode(text);
913 }
914 if (!children.empty()) {
915 output += "\n";
916 for (const auto &child : children) {
917 child.to_string_impl(output, indent_size, current_indent + indent_size);
918 }
919 output += indent_str;
920 }
921 output += "</";
922 output += tag(elem_type);
923 output += ">\n";
924 }
925 }
926
927 SVG::SVGPoints
928 SVG::SVGElement::miter_shape(SVG::SVGPoint segment_start,
929 SVG::SVGPoint segment_end,
930 SVG::SVGPoint following_segment_end) const {
931 /*
932 * Compute the stroke shape miter shape according to
933 * https://www.w3.org/TR/SVG2/painting.html#StrokeShape.
934 *
935 * The spec assumes the points of a shape are given in clockwise
936 * (mathematically negative) direction which is how Graphviz draws the points
937 * of an arrow head. A standard arrow head looks like this:
938 *
939 * 1
940 * ^
941 * /◡\
942 * / θ \
943 * / \
944 * / \
945 * / \
946 * 0 ----------- 2
947 * (3) |
948 * |
949 * |
950 * |
951 *
952 *
953 * NOTE: Graphviz draws node shapes in the opposite direction, i.e., in
954 * counter-clockwise (mathematically positive) direction which means that such
955 * points must be reordered before calling this method.
956 *
957 * See https://www.w3.org/TR/SVG2/painting.html#TermLineJoinShape for how the
958 * terminating line join shape should be calculated. Below is an attempt to
959 * copy the diagram from the spec with some details added
960 *
961 *
962 * P3
963 * /\
964 * . .
965 * l . .
966 * . .
967 * . .
968 * P1 . P2
969 * /˙·.ٜ P ٜ .·˙ \
970 * / /\ \
971 * / /◟◞\ \
972 * / / θ \ \
973 * / / \ \
974 * Aleft / A / \ B \ Bleft
975 * / / \ \
976 * / / \ \
977 * / / α /\ \ \ β-π
978 * .../....../◝...../..\.....◜ ◝.....\◝.....
979 * / / / \ ◟ \ \
980 * / / \ β \
981 * / \
982 * Aright Bright
983 *
984 * A is the current segment that ends in P.
985 * B is the following segment that starts in P.
986 *
987 * θ is the angle between the A segment and the B segment in the reverse
988 * direction
989 *
990 * α is the angle of the A segment to the x-axis.
991 *
992 * β is the angle of the B segment to the x-axis.
993 * NOTE: In the diagram above, the B segment crosses the x-axis in the
994 * downwards direction so its angle to the x-axis is in this case
995 * larger than a semi-circle (π or 180°). In the picture it is
996 * around 5π/3 or 300°. The B segment in the opposite direction has
997 * an angle to the x-axis which is β-π. This is denoted next to the
998 * Bleft line in the picture.
999 *
1000 * π is the number pi ≃ 3.14
1001 *
1002 * l is the calculated length between P1 and P3.
1003 *
1004 * The distance between P and P1 and between P and P2 is stroke-width / 2.
1005 *
1006 * NOTE: This method only implements the 'miter' join, but falls back to
1007 * 'bevel' when stroke-miterlimit is exceeded.
1008 */
1009
1010 if (segment_start == segment_end || segment_end == following_segment_end) {
1011 // the stroke shape is really a point so we just return this point without
1012 // extending it with stroke width in any direction, which seems to be the
1013 // way SVG renderers render this.
1014 return {segment_end};
1015 }
1016
1017 const auto stroke_width = attributes.stroke_width;
1018
1019 // SVG has inverted y axis so invert all y values before use
1020 const SVG::SVGPoint P = {segment_end.x, -segment_end.y};
1021 const SVG::SVGLine A = {segment_start.x, -segment_start.y, segment_end.x,
1022 -segment_end.y};
1023 const SVG::SVGLine B = {segment_end.x, -segment_end.y,
1024 following_segment_end.x, -following_segment_end.y};
1025
1026 const auto dxA = A.x2 - A.x1;
1027 const auto dyA = A.y2 - A.y1;
1028 const auto hypotA = std::hypot(dxA, dyA);
1029 const auto cosAlpha = dxA / hypotA;
1030 const auto sinAlpha = dyA / hypotA;
1031 const auto alpha = dyA > 0 ? std::acos(cosAlpha) : -std::acos(cosAlpha);
1032
1033 const SVG::SVGPoint P1 = {P.x - stroke_width / 2.0 * sinAlpha,
1034 P.y + stroke_width / 2.0 * cosAlpha};
1035
1036 const auto dxB = B.x2 - B.x1;
1037 const auto dyB = B.y2 - B.y1;
1038 const auto hypotB = std::hypot(dxB, dyB);
1039 const auto cosBeta = dxB / hypotB;
1040 const auto beta = dyB > 0 ? std::acos(cosBeta) : -std::acos(cosBeta);
1041
1042 const auto sinBeta = dyB / hypotB;
1043 const auto sinBetaMinusPi = -sinBeta;
1044 const auto cosBetaMinusPi = -cosBeta;
1045 const SVG::SVGPoint P2 = {P.x + stroke_width / 2.0 * sinBetaMinusPi,
1046 P.y - stroke_width / 2.0 * cosBetaMinusPi};
1047
1048 // angle between the A segment and the B segment in the reverse direction
1049 const auto beta_rev = beta - std::numbers::pi;
1050 const auto theta = beta_rev - alpha;
1051
1052 SVG::SVGPoints line_join_shape;
1053 const auto miter_limit = 4.0;
1054 const auto miter_length = stroke_width / std::sin(std::abs(theta) / 2.0);
1055
1056 // add the bevel, which is is the triangle formed from the three points P, P1
1057 // and P2, to the line join shape. SVG has inverted y axis so invert the
1058 // returned y value
1059 line_join_shape.emplace_back(P.x, -P.y);
1060 line_join_shape.emplace_back(P1.x, -P1.y);
1061 line_join_shape.emplace_back(P2.x, -P2.y);
1062
1063 if (miter_length > miter_limit * stroke_width) {
1064 // fall back to bevel only
1065 return line_join_shape;
1066 }
1067
1068 // length between P1 and P3 (and between P2 and P3)
1069 const auto l = stroke_width / 2.0 / std::tan(theta / 2.0);
1070
1071 const SVG::SVGPoint P3 = {P1.x + l * cosAlpha, P1.y + l * sinAlpha};
1072
1073 // SVG has inverted y axis so invert the returned y value
1074 line_join_shape.emplace_back(P3.x, -P3.y);
1075 return line_join_shape;
1076 }
1077
1078 std::string
1079 SVG::SVGElement::stroke_to_graphviz_color(const std::string &color) const {
1080 return to_graphviz_color(color);
1081 }
1082
1083 void SVG::SVGRect::extend(const SVGPoint &point) {
1084 const auto xmin = std::min(x, point.x);
1085 const auto ymin = std::min(y, point.y);
1086 const auto xmax = std::max(x + width, point.x);
1087 const auto ymax = std::max(y + height, point.y);
1088
1089 x = xmin;
1090 y = ymin;
1091 width = xmax - xmin;
1092 height = ymax - ymin;
1093 }
1094
1095 SVG::SVGPoint SVG::SVGRect::center() const {
1096 return {x + width / 2, y + height / 2};
1097 }
1098
1099 SVG::SVGRect SVG::SVGRect::intersection(SVG::SVGRect other) const {
1100 const SVG::SVGLine intersection_diagonal = {
1101 std::max(x, other.x), std::max(y, other.y),
1102 std::min(x + width, other.x + other.width),
1103 std::min(y + height, other.y + other.height)};
1104
1105 return SVG::SVGRect{
1106 .x = intersection_diagonal.x1,
1107 .y = intersection_diagonal.y1,
1108 .width = intersection_diagonal.x2 - intersection_diagonal.x1,
1109 .height = intersection_diagonal.y2 - intersection_diagonal.y1};
1110 }
1111
1112 void SVG::SVGRect::extend(const SVG::SVGRect &other) {
1113 const auto xmin = std::min(x, other.x);
1114 const auto ymin = std::min(y, other.y);
1115 const auto xmax = std::max(x + width, other.x + other.width);
1116 const auto ymax = std::max(y + height, other.y + other.height);
1117
1118 x = xmin;
1119 y = ymin;
1120 width = xmax - xmin;
1121 height = ymax - ymin;
1122 }
1123
1124 std::string_view SVG::tag(SVGElementType elem_type) {
1125 switch (elem_type) {
1126 case SVG::SVGElementType::Circle:
1127 return "circle";
1128 case SVG::SVGElementType::Ellipse:
1129 return "ellipse";
1130 case SVG::SVGElementType::Group:
1131 return "g";
1132 case SVG::SVGElementType::Line:
1133 return "line";
1134 case SVG::SVGElementType::Path:
1135 return "path";
1136 case SVG::SVGElementType::Polygon:
1137 return "polygon";
1138 case SVG::SVGElementType::Polyline:
1139 return "polyline";
1140 case SVG::SVGElementType::Rect:
1141 return "rect";
1142 case SVG::SVGElementType::Svg:
1143 return "svg";
1144 case SVG::SVGElementType::Text:
1145 return "text";
1146 case SVG::SVGElementType::Title:
1147 return "title";
1148 }
1149 UNREACHABLE();
1150 }
1151
1152 bool SVG::SVGPoint::operator==(const SVGPoint &rhs) const {
1153 return x == rhs.x && y == rhs.y;
1154 }
1155
1156 bool SVG::SVGPoint::operator!=(const SVGPoint &rhs) const {
1157 return !(*this == rhs);
1158 }
1159
1160 bool SVG::SVGPoint::is_higher_than(const SVGPoint &other) const {
1161 // SVG uses inverted y axis, so smaller is higher
1162 return y < other.y;
1163 }
1164
1165 bool SVG::SVGPoint::is_lower_than(const SVGPoint &other) const {
1166 // SVG uses inverted y axis, so larger is lower
1167 return y > other.y;
1168 }
1169
1170 bool SVG::SVGPoint::is_more_left_than(const SVGPoint &other) const {
1171 return x < other.x;
1172 }
1173
1174 bool SVG::SVGPoint::is_more_right_than(const SVGPoint &other) const {
1175 return x > other.x;
1176 }