1use std::sync::Arc;
5
6use strict_num::NonZeroPositiveF32;
7use svgtypes::Length;
8use tiny_skia_path::Point;
9
10use super::converter;
11use super::svgtree::{AId, EId, SvgNode};
12use crate::{
13 ApproxEqUlps, ApproxZeroUlps, ClipPath, Fill, Group, Node, NonZeroRect, Path, Transform,
14 ViewBox,
15};
16
17#[derive(Copy, Clone, Debug)]
19enum Segment {
20 MoveTo(Point),
21 LineTo(Point),
22 CubicTo(Point, Point, Point),
23 Close,
24}
25
26pub(crate) fn is_valid(node: SvgNode) -> bool {
27 if node
29 .ancestors()
30 .any(|n| n.tag_name() == Some(EId::ClipPath))
31 {
32 return false;
33 }
34
35 let start = node.find_attribute::<SvgNode>(AId::MarkerStart);
36 let mid = node.find_attribute::<SvgNode>(AId::MarkerMid);
37 let end = node.find_attribute::<SvgNode>(AId::MarkerEnd);
38 start.is_some() || mid.is_some() || end.is_some()
39}
40
41pub(crate) fn convert(
42 node: SvgNode,
43 path: &tiny_skia_path::Path,
44 state: &converter::State,
45 cache: &mut converter::Cache,
46 parent: &mut Group,
47) {
48 let list = [
49 (AId::MarkerStart, MarkerKind::Start),
50 (AId::MarkerMid, MarkerKind::Middle),
51 (AId::MarkerEnd, MarkerKind::End),
52 ];
53
54 for (aid, kind) in &list {
55 let mut marker = None;
56 if let Some(link) = node.find_attribute::<SvgNode>(*aid) {
57 if link.tag_name() == Some(EId::Marker) {
58 marker = Some(link);
59 }
60 }
61
62 if let Some(marker) = marker {
63 resolve(node, path, marker, *kind, state, cache, parent);
64 }
65 }
66}
67
68#[derive(Clone, Copy)]
69enum MarkerKind {
70 Start,
71 Middle,
72 End,
73}
74
75enum MarkerOrientation {
76 Auto,
77 AutoStartReverse,
78 Angle(f32),
79}
80
81fn resolve(
82 shape_node: SvgNode,
83 path: &tiny_skia_path::Path,
84 marker_node: SvgNode,
85 marker_kind: MarkerKind,
86 state: &converter::State,
87 cache: &mut converter::Cache,
88 parent: &mut Group,
89) -> Option<()> {
90 let stroke_scale = stroke_scale(shape_node, marker_node, state)?.get();
91
92 let r = convert_rect(marker_node, state)?;
93
94 let view_box_ts = marker_node
95 .parse_viewbox()
96 .map(|vb| {
97 ViewBox {
98 rect: vb,
99 aspect: marker_node
100 .attribute(AId::PreserveAspectRatio)
101 .unwrap_or_default(),
102 }
103 .to_transform(r.size())
104 })
105 .unwrap_or_default();
106
107 let has_overflow = {
108 let overflow = marker_node.attribute(AId::Overflow);
109 overflow.is_none() || overflow == Some("hidden") || overflow == Some("scroll")
111 };
112
113 let clip_path = if has_overflow {
114 let clip_rect = r
115 .size()
116 .to_non_zero_rect(0.0, 0.0)
117 .transform(view_box_ts.invert()?)?;
118
119 let mut clip_path = ClipPath::empty(cache.gen_clip_path_id());
120
121 let mut path = Path::new_simple(Arc::new(tiny_skia_path::PathBuilder::from_rect(
122 clip_rect.to_rect(),
123 )));
124 path.fill = Some(Fill::default());
125
126 clip_path.root.children.push(Node::Path(Box::new(path)));
127
128 Some(Arc::new(clip_path))
129 } else {
130 None
131 };
132
133 let mut segments: Vec<Segment> = Vec::with_capacity(path.len());
135 let mut prev = Point::zero();
136 let mut prev_move = Point::zero();
137 for seg in path.segments() {
138 match seg {
139 tiny_skia_path::PathSegment::MoveTo(p) => {
140 segments.push(Segment::MoveTo(p));
141 prev = p;
142 prev_move = p;
143 }
144 tiny_skia_path::PathSegment::LineTo(p) => {
145 segments.push(Segment::LineTo(p));
146 prev = p;
147 }
148 tiny_skia_path::PathSegment::QuadTo(p1, p) => {
149 let (p1, p2, p) = quad_to_curve(prev, p1, p);
150 segments.push(Segment::CubicTo(p1, p2, p));
151 prev = p;
152 }
153 tiny_skia_path::PathSegment::CubicTo(p1, p2, p) => {
154 segments.push(Segment::CubicTo(p1, p2, p));
155 prev = p;
156 }
157 tiny_skia_path::PathSegment::Close => {
158 segments.push(Segment::Close);
159 prev = prev_move;
160 }
161 }
162 }
163
164 let draw_marker = |p: tiny_skia_path::Point, idx: usize| {
165 let mut ts = Transform::from_translate(p.x, p.y);
166
167 let angle = match convert_orientation(marker_node) {
168 MarkerOrientation::AutoStartReverse if idx == 0 => {
169 (calc_vertex_angle(&segments, idx) + 180.0) % 360.0
170 }
171 MarkerOrientation::Auto | MarkerOrientation::AutoStartReverse => {
172 calc_vertex_angle(&segments, idx)
173 }
174 MarkerOrientation::Angle(angle) => angle,
175 };
176
177 if !angle.approx_zero_ulps(4) {
178 ts = ts.pre_rotate(angle);
179 }
180
181 let (sx, sy) = view_box_ts.get_scale();
182 ts = ts.pre_scale(sx * stroke_scale, sy * stroke_scale);
183 ts = ts.pre_translate(-r.x(), -r.y());
184
185 let mut g = Group {
187 transform: ts,
188 abs_transform: parent.abs_transform.pre_concat(ts),
189 clip_path: clip_path.clone(),
190 ..Group::empty()
191 };
192
193 let mut marker_state = state.clone();
194 marker_state.inside_marker = true;
195 converter::convert_children(marker_node, &marker_state, cache, &mut g);
196
197 if g.has_children() {
198 parent.children.push(Node::Group(Box::new(g)));
199 }
200 };
201
202 draw_markers(&segments, marker_kind, draw_marker);
203
204 Some(())
205}
206
207fn stroke_scale(
208 path_node: SvgNode,
209 marker_node: SvgNode,
210 state: &converter::State,
211) -> Option<NonZeroPositiveF32> {
212 match marker_node.attribute(AId::MarkerUnits) {
213 Some("userSpaceOnUse") => NonZeroPositiveF32::new(1.0),
214 _ => path_node.resolve_valid_length(AId::StrokeWidth, state, 1.0),
215 }
216}
217
218fn draw_markers<P>(path: &[Segment], kind: MarkerKind, mut draw_marker: P)
219where
220 P: FnMut(tiny_skia_path::Point, usize),
221{
222 match kind {
223 MarkerKind::Start => {
224 if let Some(Segment::MoveTo(p)) = path.first().cloned() {
225 draw_marker(p, 0);
226 }
227 }
228 MarkerKind::Middle => {
229 let total = path.len() - 1;
230 let mut i = 1;
231 while i < total {
232 let p = match path[i] {
233 Segment::MoveTo(p) => p,
234 Segment::LineTo(p) => p,
235 Segment::CubicTo(_, _, p) => p,
236 _ => {
237 i += 1;
238 continue;
239 }
240 };
241
242 draw_marker(p, i);
243
244 i += 1;
245 }
246 }
247 MarkerKind::End => {
248 let idx = path.len() - 1;
249 match path.last().cloned() {
250 Some(Segment::LineTo(p)) => {
251 draw_marker(p, idx);
252 }
253 Some(Segment::CubicTo(_, _, p)) => {
254 draw_marker(p, idx);
255 }
256 Some(Segment::Close) => {
257 let p = get_subpath_start(path, idx);
258 draw_marker(p, idx);
259 }
260 _ => {}
261 }
262 }
263 }
264}
265
266fn calc_vertex_angle(path: &[Segment], idx: usize) -> f32 {
267 if idx == 0 {
268 debug_assert!(path.len() > 1);
271
272 let seg1 = path[0];
273 let seg2 = path[1];
274
275 match (seg1, seg2) {
276 (Segment::MoveTo(pm), Segment::LineTo(p)) => calc_line_angle(pm.x, pm.y, p.x, p.y),
277 (Segment::MoveTo(pm), Segment::CubicTo(p1, _, p)) => {
278 if pm.x.approx_eq_ulps(&p1.x, 4) && pm.y.approx_eq_ulps(&p1.y, 4) {
279 calc_line_angle(pm.x, pm.y, p.x, p.y)
280 } else {
281 calc_line_angle(pm.x, pm.y, p1.x, p1.y)
282 }
283 }
284 _ => 0.0,
285 }
286 } else if idx == path.len() - 1 {
287 let seg1 = path[idx - 1];
290 let seg2 = path[idx];
291
292 match (seg1, seg2) {
293 (_, Segment::MoveTo(_)) => 0.0, (_, Segment::LineTo(p)) => {
295 let prev = get_prev_vertex(path, idx);
296 calc_line_angle(prev.x, prev.y, p.x, p.y)
297 }
298 (_, Segment::CubicTo(p1, p2, p)) => {
299 if p2.x.approx_eq_ulps(&p.x, 4) && p2.y.approx_eq_ulps(&p.y, 4) {
300 calc_line_angle(p1.x, p1.y, p.x, p.y)
301 } else {
302 calc_line_angle(p2.x, p2.y, p.x, p.y)
303 }
304 }
305 (Segment::LineTo(p), Segment::Close) => {
306 let next = get_subpath_start(path, idx);
307 calc_line_angle(p.x, p.y, next.x, next.y)
308 }
309 (Segment::CubicTo(_, p2, p), Segment::Close) => {
310 let prev = get_prev_vertex(path, idx);
311 let next = get_subpath_start(path, idx);
312 calc_curves_angle(
313 prev.x, prev.y, p2.x, p2.y, p.x, p.y, next.x, next.y, next.x, next.y,
314 )
315 }
316 (_, Segment::Close) => 0.0,
317 }
318 } else {
319 let seg1 = path[idx];
322 let seg2 = path[idx + 1];
323
324 match (seg1, seg2) {
326 (Segment::MoveTo(pm), Segment::LineTo(p)) => calc_line_angle(pm.x, pm.y, p.x, p.y),
327 (Segment::MoveTo(pm), Segment::CubicTo(p1, _, _)) => {
328 calc_line_angle(pm.x, pm.y, p1.x, p1.y)
329 }
330 (Segment::LineTo(p1), Segment::LineTo(p2)) => {
331 let prev = get_prev_vertex(path, idx);
332 calc_angle(prev.x, prev.y, p1.x, p1.y, p1.x, p1.y, p2.x, p2.y)
333 }
334 (Segment::CubicTo(_, c1_p2, c1_p), Segment::CubicTo(c2_p1, _, c2_p)) => {
335 let prev = get_prev_vertex(path, idx);
336 calc_curves_angle(
337 prev.x, prev.y, c1_p2.x, c1_p2.y, c1_p.x, c1_p.y, c2_p1.x, c2_p1.y, c2_p.x,
338 c2_p.y,
339 )
340 }
341 (Segment::LineTo(pl), Segment::CubicTo(p1, _, p)) => {
342 let prev = get_prev_vertex(path, idx);
343 calc_curves_angle(
344 prev.x, prev.y, prev.x, prev.y, pl.x, pl.y, p1.x, p1.y, p.x, p.y,
345 )
346 }
347 (Segment::CubicTo(_, p2, p), Segment::LineTo(pl)) => {
348 let prev = get_prev_vertex(path, idx);
349 calc_curves_angle(prev.x, prev.y, p2.x, p2.y, p.x, p.y, pl.x, pl.y, pl.x, pl.y)
350 }
351 (Segment::LineTo(p), Segment::MoveTo(_)) => {
352 let prev = get_prev_vertex(path, idx);
353 calc_line_angle(prev.x, prev.y, p.x, p.y)
354 }
355 (Segment::CubicTo(_, p2, p), Segment::MoveTo(_)) => {
356 if p.x.approx_eq_ulps(&p2.x, 4) && p.y.approx_eq_ulps(&p2.y, 4) {
357 let prev = get_prev_vertex(path, idx);
358 calc_line_angle(prev.x, prev.y, p.x, p.y)
359 } else {
360 calc_line_angle(p2.x, p2.y, p.x, p.y)
361 }
362 }
363 (Segment::LineTo(p), Segment::Close) => {
364 let prev = get_prev_vertex(path, idx);
365 let next = get_subpath_start(path, idx);
366 calc_angle(prev.x, prev.y, p.x, p.y, p.x, p.y, next.x, next.y)
367 }
368 (_, Segment::Close) => {
369 let prev = get_prev_vertex(path, idx);
370 let next = get_subpath_start(path, idx);
371 calc_line_angle(prev.x, prev.y, next.x, next.y)
372 }
373 (_, Segment::MoveTo(_)) | (Segment::Close, _) => 0.0,
374 }
375 }
376}
377
378fn calc_line_angle(x1: f32, y1: f32, x2: f32, y2: f32) -> f32 {
379 calc_angle(x1, y1, x2, y2, x1, y1, x2, y2)
380}
381
382fn calc_curves_angle(
383 px: f32,
384 py: f32, cx1: f32,
386 cy1: f32, x: f32,
388 y: f32, cx2: f32,
390 cy2: f32, nx: f32,
392 ny: f32, ) -> f32 {
394 if cx1.approx_eq_ulps(&x, 4) && cy1.approx_eq_ulps(&y, 4) {
395 calc_angle(px, py, x, y, x, y, cx2, cy2)
396 } else if x.approx_eq_ulps(&cx2, 4) && y.approx_eq_ulps(&cy2, 4) {
397 calc_angle(cx1, cy1, x, y, x, y, nx, ny)
398 } else {
399 calc_angle(cx1, cy1, x, y, x, y, cx2, cy2)
400 }
401}
402
403fn calc_angle(x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32, x4: f32, y4: f32) -> f32 {
404 use std::f32::consts::*;
405
406 fn normalize(rad: f32) -> f32 {
407 let v = rad % (PI * 2.0);
408 if v < 0.0 { v + PI * 2.0 } else { v }
409 }
410
411 fn vector_angle(vx: f32, vy: f32) -> f32 {
412 let rad = vy.atan2(vx);
413 if rad.is_nan() { 0.0 } else { normalize(rad) }
414 }
415
416 let in_a = vector_angle(x2 - x1, y2 - y1);
417 let out_a = vector_angle(x4 - x3, y4 - y3);
418 let d = (out_a - in_a) * 0.5;
419
420 let mut angle = in_a + d;
421 if FRAC_PI_2 < d.abs() {
422 angle -= PI;
423 }
424
425 normalize(angle).to_degrees()
426}
427
428fn get_subpath_start(segments: &[Segment], idx: usize) -> tiny_skia_path::Point {
429 let offset = segments.len() - idx;
430 for seg in segments.iter().rev().skip(offset) {
431 if let Segment::MoveTo(p) = *seg {
432 return p;
433 }
434 }
435
436 tiny_skia_path::Point::zero()
437}
438
439fn get_prev_vertex(segments: &[Segment], idx: usize) -> tiny_skia_path::Point {
440 match segments[idx - 1] {
441 Segment::MoveTo(p) => p,
442 Segment::LineTo(p) => p,
443 Segment::CubicTo(_, _, p) => p,
444 Segment::Close => get_subpath_start(segments, idx),
445 }
446}
447
448fn convert_rect(node: SvgNode, state: &converter::State) -> Option<NonZeroRect> {
449 NonZeroRect::from_xywh(
450 node.convert_user_length(AId::RefX, state, Length::zero()),
451 node.convert_user_length(AId::RefY, state, Length::zero()),
452 node.convert_user_length(AId::MarkerWidth, state, Length::new_number(3.0)),
453 node.convert_user_length(AId::MarkerHeight, state, Length::new_number(3.0)),
454 )
455}
456
457fn convert_orientation(node: SvgNode) -> MarkerOrientation {
458 match node.attribute(AId::Orient) {
459 Some("auto") => MarkerOrientation::Auto,
460 Some("auto-start-reverse") => MarkerOrientation::AutoStartReverse,
461 _ => match node.attribute::<svgtypes::Angle>(AId::Orient) {
462 Some(angle) => MarkerOrientation::Angle(angle.to_degrees() as f32),
463 None => MarkerOrientation::Angle(0.0),
464 },
465 }
466}
467
468fn quad_to_curve(prev: Point, p1: Point, p: Point) -> (Point, Point, Point) {
469 #[inline]
470 fn calc(n1: f32, n2: f32) -> f32 {
471 (n1 + n2 * 2.0) / 3.0
472 }
473
474 (
475 Point::from_xy(calc(prev.x, p1.x), calc(prev.y, p1.y)),
476 Point::from_xy(calc(p.x, p1.x), calc(p.y, p1.y)),
477 p,
478 )
479}