Skip to main content

takumi_core/
path_data.rs

1//! Compact SVG path `d` data, as SVG output and the paint document write it.
2
3use std::{
4  f64::consts::{FRAC_PI_2, TAU},
5  fmt::{self, Write as _},
6};
7
8use crate::{
9  geometry::{PathCommand, Point, Rect},
10  style::Affine,
11};
12
13/// Numbers a single path command serializes (a cubic carries three coordinate
14/// pairs), used with [`APPROX_CHARS_PER_NUMBER`] to presize the path buffer.
15const NUMBERS_PER_COMMAND: usize = 6;
16
17/// Compact SVG path `d` data, eliding repeated commands and separators the grammar does not need.
18pub struct PathData {
19  out: String,
20  prev_was_number: bool,
21  prev_had_dot: bool,
22  last_command: Option<u8>,
23}
24
25impl PathData {
26  /// Path commands up to the first error and whether all parsed, normalized as Blink's
27  /// `SVGPathNormalizer`.
28  pub fn parse(text: &str) -> (Vec<PathCommand>, bool) {
29    let mut scanner = Scanner::new(text);
30    let mut normalizer = Normalizer::default();
31    let mut previous_command = None;
32
33    loop {
34      scanner.skip_spaces();
35
36      if scanner.at_end() {
37        return (normalizer.commands, true);
38      }
39
40      let Some((absolute, segment)) = scanner.segment(&mut previous_command) else {
41        return (normalizer.commands, false);
42      };
43
44      if !normalizer.push(absolute, segment) {
45        return (normalizer.commands, false);
46      }
47    }
48  }
49
50  /// An empty path with room for `capacity` bytes.
51  pub fn with_capacity(capacity: usize) -> Self {
52    Self {
53      out: String::with_capacity(capacity),
54      prev_was_number: false,
55      prev_had_dot: false,
56      last_command: None,
57    }
58  }
59
60  /// Writes a command letter unless the grammar lets it repeat implicitly. Pairs after a moveto
61  /// are linetos, so a second moveto keeps its letter.
62  pub fn command(&mut self, letter: u8) {
63    let elide = matches!(self.last_command, Some(prev) if (prev == letter && !matches!(letter, b'M' | b'm'))
64      || (prev == b'M' && letter == b'L')
65      || (prev == b'm' && letter == b'l'));
66    if !elide {
67      self.out.push(letter as char);
68      self.prev_was_number = false;
69    }
70    self.last_command = Some(letter);
71  }
72
73  /// Writes a number.
74  pub fn number(&mut self, value: f32) {
75    let mut buf = NumBuf::new();
76    let text = Num(value).format(&mut buf);
77    let first = text.as_bytes()[0];
78    if self.prev_was_number && first != b'-' && !(first == b'.' && self.prev_had_dot) {
79      self.out.push(' ');
80    }
81    self.out.push_str(text);
82    self.prev_was_number = true;
83    self.prev_had_dot = text.contains('.');
84  }
85
86  /// Writes a coordinate pair.
87  pub fn pair(&mut self, x: f32, y: f32) {
88    self.number(x);
89    self.number(y);
90  }
91
92  /// Closes the subpath.
93  pub fn close(&mut self) {
94    self.out.push('Z');
95    self.prev_was_number = false;
96    self.last_command = None;
97  }
98
99  /// The path data written so far.
100  pub fn into_string(self) -> String {
101    self.out
102  }
103}
104
105/// Path coordinates keep two decimals, one fewer than [`Num`], whose transforms multiply error.
106const PATH_COORD_FACTOR: f32 = 100.0;
107/// Tolerance (one grid step) for treating a curve's control point as the exact
108/// reflection of the previous one, enabling the `s`/`t` shorthands.
109const REFLECT_TOLERANCE: f32 = 1.0 / PATH_COORD_FACTOR;
110
111/// Rounds a path coordinate to the grid path data keeps.
112pub fn quantize_path(value: f32) -> f32 {
113  (value * PATH_COORD_FACTOR).round() / PATH_COORD_FACTOR
114}
115
116/// Serializes `commands` under `transform` to relative path data, carrying rounding error forward
117/// so contours stay closed, as SVGO's `convertPathData` does.
118pub fn path_data(commands: &[PathCommand], transform: Affine) -> String {
119  let [a, b, c, d, e, f] = transform.to_cols_array();
120  let path =
121    PathData::with_capacity(commands.len() * NUMBERS_PER_COMMAND * APPROX_CHARS_PER_NUMBER);
122  let map = |p: Point<f32>| (a * p.x + c * p.y + e, b * p.x + d * p.y + f);
123  let mut emit = RelEmit::new(path);
124  for command in commands {
125    match command {
126      PathCommand::MoveTo(p) => {
127        let (x, y) = map(*p);
128        emit.move_to(x, y);
129      }
130      PathCommand::LineTo(p) => {
131        let (x, y) = map(*p);
132        emit.line_to(x, y);
133      }
134      PathCommand::QuadTo(c0, p) => {
135        let (cx, cy) = map(*c0);
136        let (x, y) = map(*p);
137        emit.quad_to(cx, cy, x, y);
138      }
139      PathCommand::CubicTo(c0, c1, p) => {
140        let (c1x, c1y) = map(*c0);
141        let (c2x, c2y) = map(*c1);
142        let (x, y) = map(*p);
143        emit.cubic_to(c1x, c1y, c2x, c2y, x, y);
144      }
145      PathCommand::Close => emit.close(),
146    }
147  }
148  emit.finish()
149}
150
151/// The control point of the previous curve (reconstructed in absolute space),
152/// used to detect smooth joins for the `s`/`t` shorthands.
153#[derive(Clone, Copy)]
154enum PrevControl {
155  None,
156  Cubic(f32, f32),
157  Quad(f32, f32),
158}
159
160/// Writes relative commands into a [`PathData`] from the quantized pen position.
161struct RelEmit {
162  path: PathData,
163  x: f32,
164  y: f32,
165  start_x: f32,
166  start_y: f32,
167  started: bool,
168  prev: PrevControl,
169}
170
171impl RelEmit {
172  fn new(path: PathData) -> Self {
173    Self {
174      path,
175      x: 0.0,
176      y: 0.0,
177      start_x: 0.0,
178      start_y: 0.0,
179      started: false,
180      prev: PrevControl::None,
181    }
182  }
183
184  /// Advances the reconstructed pen by an already-quantized delta.
185  fn advance(&mut self, dx: f32, dy: f32) {
186    self.x = quantize_path(self.x + dx);
187    self.y = quantize_path(self.y + dy);
188  }
189
190  fn move_to(&mut self, x: f32, y: f32) {
191    if self.started {
192      let (dx, dy) = (quantize_path(x - self.x), quantize_path(y - self.y));
193      self.path.command(b'm');
194      self.path.pair(dx, dy);
195      self.advance(dx, dy);
196    } else {
197      let (qx, qy) = (quantize_path(x), quantize_path(y));
198      self.path.command(b'M');
199      self.path.pair(qx, qy);
200      self.x = qx;
201      self.y = qy;
202      self.started = true;
203    }
204    self.start_x = self.x;
205    self.start_y = self.y;
206    self.prev = PrevControl::None;
207  }
208
209  fn line_to(&mut self, x: f32, y: f32) {
210    let (dx, dy) = (quantize_path(x - self.x), quantize_path(y - self.y));
211    if dx == 0.0 && dy == 0.0 {
212      return;
213    }
214    if dy == 0.0 {
215      self.path.command(b'h');
216      self.path.number(dx);
217    } else if dx == 0.0 {
218      self.path.command(b'v');
219      self.path.number(dy);
220    } else {
221      self.path.command(b'l');
222      self.path.pair(dx, dy);
223    }
224    self.advance(dx, dy);
225    self.prev = PrevControl::None;
226  }
227
228  fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) {
229    let (ox, oy) = (self.x, self.y);
230    let (dx, dy) = (quantize_path(x - ox), quantize_path(y - oy));
231    let control = match self.prev {
232      PrevControl::Quad(px, py) if near(cx, 2.0 * ox - px) && near(cy, 2.0 * oy - py) => {
233        self.path.command(b't');
234        self.path.pair(dx, dy);
235        (2.0 * ox - px, 2.0 * oy - py)
236      }
237      _ => {
238        let (dcx, dcy) = (quantize_path(cx - ox), quantize_path(cy - oy));
239        self.path.command(b'q');
240        self.path.pair(dcx, dcy);
241        self.path.pair(dx, dy);
242        (ox + dcx, oy + dcy)
243      }
244    };
245    self.advance(dx, dy);
246    self.prev = PrevControl::Quad(control.0, control.1);
247  }
248
249  fn cubic_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32) {
250    let (ox, oy) = (self.x, self.y);
251    let (dx, dy) = (quantize_path(x - ox), quantize_path(y - oy));
252    let (dc2x, dc2y) = (quantize_path(c2x - ox), quantize_path(c2y - oy));
253    match self.prev {
254      PrevControl::Cubic(px, py) if near(c1x, 2.0 * ox - px) && near(c1y, 2.0 * oy - py) => {
255        self.path.command(b's');
256      }
257      _ => {
258        self.path.command(b'c');
259        self
260          .path
261          .pair(quantize_path(c1x - ox), quantize_path(c1y - oy));
262      }
263    }
264    self.path.pair(dc2x, dc2y);
265    self.path.pair(dx, dy);
266    self.advance(dx, dy);
267    self.prev = PrevControl::Cubic(ox + dc2x, oy + dc2y);
268  }
269
270  fn close(&mut self) {
271    self.path.close();
272    self.x = self.start_x;
273    self.y = self.start_y;
274    self.prev = PrevControl::None;
275  }
276
277  fn finish(self) -> String {
278    self.path.into_string()
279  }
280}
281
282fn near(a: f32, b: f32) -> bool {
283  (a - b).abs() < REFLECT_TOLERANCE
284}
285
286/// Builds the `d` data for an axis-aligned rectangle from its edges.
287pub fn edges_path_data(edges: Rect<f32>) -> String {
288  let mut path = PathData::with_capacity(5 * APPROX_CHARS_PER_NUMBER);
289  path.command(b'M');
290  path.pair(edges.left, edges.top);
291  path.command(b'H');
292  path.number(edges.right);
293  path.command(b'V');
294  path.number(edges.bottom);
295  path.command(b'H');
296  path.number(edges.left);
297  path.close();
298  path.into_string()
299}
300
301/// Coordinates, dimensions, and opacities keep three decimals.
302const COORD_FACTOR: f32 = 1000.0;
303
304/// Rough characters one quantized number serializes to, used to presize buffers.
305pub const APPROX_CHARS_PER_NUMBER: usize = 8;
306
307/// A number for SVG output on [`COORD_FACTOR`]'s grid, `0` when not finite.
308pub struct Num(pub f32);
309
310/// Stack buffer for one formatted number. 48 bytes holds any `f32` Display.
311struct NumBuf {
312  bytes: [u8; 48],
313  len: usize,
314}
315
316impl NumBuf {
317  const fn new() -> Self {
318    Self {
319      bytes: [0; 48],
320      len: 0,
321    }
322  }
323
324  fn push(&mut self, byte: u8) {
325    self.bytes[self.len] = byte;
326    self.len += 1;
327  }
328
329  /// Writes `digits` decimal digits of `value`, zero-padded on the left.
330  fn push_digits(&mut self, value: u32, digits: usize) {
331    for place in (0..digits).rev() {
332      self.push(b'0' + (value / 10u32.pow(place as u32) % 10) as u8);
333    }
334  }
335
336  fn as_str(&self) -> &str {
337    str::from_utf8(&self.bytes[..self.len]).unwrap_or("0")
338  }
339}
340
341impl fmt::Write for NumBuf {
342  fn write_str(&mut self, s: &str) -> fmt::Result {
343    let end = self.len + s.len();
344    if end > self.bytes.len() {
345      return Err(fmt::Error);
346    }
347    self.bytes[self.len..end].copy_from_slice(s.as_bytes());
348    self.len = end;
349    Ok(())
350  }
351}
352
353impl Num {
354  /// Formats the number into `buf` and returns its text.
355  fn format<'b>(&self, buf: &'b mut NumBuf) -> &'b str {
356    if !self.0.is_finite() {
357      return "0";
358    }
359    let units = (self.0 * COORD_FACTOR).round();
360    if units == 0.0 {
361      return "0";
362    }
363    // An `f32` round-trips every decimal of up to six significant digits, so the shortest
364    // representation of `units / COORD_FACTOR` is that decimal as written.
365    if units.abs() < 1_000_000.0 {
366      let units = units as i32;
367      let magnitude = units.unsigned_abs();
368      let (whole, mut fraction) = (magnitude / 1000, magnitude % 1000);
369
370      if units < 0 {
371        buf.push(b'-');
372      }
373      if whole > 0 {
374        buf.push_digits(whole, whole.ilog10() as usize + 1);
375      }
376      if fraction > 0 {
377        let mut digits = 3;
378
379        while fraction % 10 == 0 {
380          fraction /= 10;
381          digits -= 1;
382        }
383        buf.push(b'.');
384        buf.push_digits(fraction, digits);
385      }
386      return buf.as_str();
387    }
388    let _ = write!(buf, "{}", units / COORD_FACTOR);
389    buf.as_str()
390  }
391}
392
393impl fmt::Display for Num {
394  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
395    f.write_str(self.format(&mut NumBuf::new()))
396  }
397}
398
399impl PathData {
400  /// The points of a `points` attribute: pairs of numbers, up to the first thing that is not one.
401  #[cfg(feature = "svg")]
402  pub(crate) fn parse_points(text: &str) -> Vec<Point<f32>> {
403    let mut scanner = Scanner::new(text);
404    let mut points = Vec::new();
405
406    while !scanner.at_end() {
407      let Some((x, y)) = scanner.pair() else {
408        break;
409      };
410
411      points.push(single((x, y)));
412    }
413
414    points
415  }
416}
417
418/// Reads the numbers of an SVG attribute byte by byte, after svgtypes' `Stream`.
419struct Scanner<'a> {
420  bytes: &'a [u8],
421  position: usize,
422}
423
424/// One path data segment as authored, before it is made absolute.
425enum Segment {
426  MoveTo(f64, f64),
427  LineTo(f64, f64),
428  Horizontal(f64),
429  Vertical(f64),
430  Cubic([f64; 6]),
431  SmoothCubic([f64; 4]),
432  Quadratic([f64; 4]),
433  SmoothQuadratic(f64, f64),
434  Arc(ArcSegment),
435  Close,
436}
437
438struct ArcSegment {
439  radii: (f64, f64),
440  rotation: f64,
441  large_arc: bool,
442  sweep: bool,
443  to: (f64, f64),
444}
445
446impl<'a> Scanner<'a> {
447  fn new(text: &'a str) -> Self {
448    Self {
449      bytes: text.as_bytes(),
450      position: 0,
451    }
452  }
453
454  fn at_end(&self) -> bool {
455    self.position >= self.bytes.len()
456  }
457
458  fn peek(&self) -> Option<u8> {
459    self.bytes.get(self.position).copied()
460  }
461
462  fn skip_spaces(&mut self) {
463    while self
464      .peek()
465      .is_some_and(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))
466    {
467      self.position += 1;
468    }
469  }
470
471  fn skip_digits(&mut self) {
472    while self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
473      self.position += 1;
474    }
475  }
476
477  /// A number, where `e` not followed by `m` or `x` starts an exponent.
478  fn number(&mut self) -> Option<f64> {
479    self.skip_spaces();
480
481    let start = self.position;
482    let mut byte = self.peek()?;
483
484    if matches!(byte, b'+' | b'-') {
485      self.position += 1;
486      byte = self.peek()?;
487    }
488
489    match byte {
490      b'0'..=b'9' => self.skip_digits(),
491      b'.' => {}
492      _ => return None,
493    }
494
495    if self.peek() == Some(b'.') {
496      self.position += 1;
497      self.skip_digits();
498    }
499
500    if matches!(self.peek(), Some(b'e' | b'E')) {
501      let next = *self.bytes.get(self.position + 1)?;
502
503      if next != b'm' && next != b'x' {
504        self.position += 1;
505
506        match self.peek()? {
507          b'+' | b'-' => {
508            self.position += 1;
509            self.skip_digits();
510          }
511          b'0'..=b'9' => self.skip_digits(),
512          _ => return None,
513        }
514      }
515    }
516
517    let number = str::from_utf8(self.bytes.get(start..self.position)?)
518      .ok()?
519      .parse::<f64>()
520      .ok()?;
521
522    (number as f32).is_finite().then_some(number)
523  }
524
525  /// A number followed by its optional comma separator.
526  fn list_number(&mut self) -> Option<f64> {
527    if self.at_end() {
528      return None;
529    }
530
531    let number = self.number()?;
532
533    self.skip_spaces();
534    self.skip_comma();
535
536    Some(number)
537  }
538
539  fn skip_comma(&mut self) {
540    if self.peek() == Some(b',') {
541      self.position += 1;
542    }
543  }
544
545  /// An arc flag, which may sit directly against the next one without a separator.
546  fn flag(&mut self) -> Option<bool> {
547    self.skip_spaces();
548
549    let flag = match self.peek()? {
550      b'0' => false,
551      b'1' => true,
552      _ => return None,
553    };
554
555    self.position += 1;
556    self.skip_spaces();
557    self.skip_comma();
558    self.skip_spaces();
559
560    Some(flag)
561  }
562
563  fn pair(&mut self) -> Option<(f64, f64)> {
564    Some((self.list_number()?, self.list_number()?))
565  }
566
567  /// The next segment and whether its coordinates are absolute. `previous_command` is the last
568  /// command letter, which a number with no letter repeats (a moveto repeats as a lineto).
569  fn segment(&mut self, previous_command: &mut Option<u8>) -> Option<(bool, Segment)> {
570    let first = self.peek()?;
571
572    if previous_command.is_none() && !matches!(first, b'M' | b'm') {
573      return None;
574    }
575
576    let (command, implicit_moveto) = if is_command(first) {
577      self.position += 1;
578
579      (first, false)
580    } else if matches!(first, b'0'..=b'9' | b'.' | b'-' | b'+') {
581      match (*previous_command)? {
582        b'Z' | b'z' => return None,
583        b'M' => (b'L', true),
584        b'm' => (b'l', true),
585        repeated => (repeated, false),
586      }
587    } else {
588      return None;
589    };
590
591    let absolute = command.is_ascii_uppercase();
592    let segment = match command.to_ascii_lowercase() {
593      b'm' => {
594        let (x, y) = self.pair()?;
595
596        Segment::MoveTo(x, y)
597      }
598      b'l' => {
599        let (x, y) = self.pair()?;
600
601        Segment::LineTo(x, y)
602      }
603      b'h' => Segment::Horizontal(self.list_number()?),
604      b'v' => Segment::Vertical(self.list_number()?),
605      b'c' => Segment::Cubic([
606        self.list_number()?,
607        self.list_number()?,
608        self.list_number()?,
609        self.list_number()?,
610        self.list_number()?,
611        self.list_number()?,
612      ]),
613      b's' => Segment::SmoothCubic([
614        self.list_number()?,
615        self.list_number()?,
616        self.list_number()?,
617        self.list_number()?,
618      ]),
619      b'q' => Segment::Quadratic([
620        self.list_number()?,
621        self.list_number()?,
622        self.list_number()?,
623        self.list_number()?,
624      ]),
625      b't' => {
626        let (x, y) = self.pair()?;
627
628        Segment::SmoothQuadratic(x, y)
629      }
630      b'a' => Segment::Arc(ArcSegment {
631        radii: self.pair()?,
632        rotation: self.list_number()?,
633        large_arc: self.flag()?,
634        sweep: self.flag()?,
635        to: self.pair()?,
636      }),
637      _ => Segment::Close,
638    };
639
640    *previous_command = Some(match (implicit_moveto, absolute) {
641      (true, true) => b'M',
642      (true, false) => b'm',
643      (false, _) => command,
644    });
645
646    Some((absolute, segment))
647  }
648}
649
650fn is_command(byte: u8) -> bool {
651  matches!(
652    byte.to_ascii_lowercase(),
653    b'm' | b'z' | b'l' | b'h' | b'v' | b'c' | b's' | b'q' | b't' | b'a'
654  )
655}
656
657/// What the last segment leaves a smooth curve to reflect.
658#[derive(Clone, Copy, Default)]
659enum Reflection {
660  #[default]
661  None,
662  Cubic {
663    control: (f64, f64),
664    end: (f64, f64),
665  },
666  Quadratic {
667    control: (f64, f64),
668    end: (f64, f64),
669  },
670  SmoothQuadratic {
671    end: (f64, f64),
672  },
673}
674
675/// Makes segments absolute and appends them as [`PathCommand`]s, after svgtypes'
676/// `SimplifyingPathParser`.
677#[derive(Default)]
678struct Normalizer {
679  commands: Vec<PathCommand>,
680  current: (f64, f64),
681  subpath_start: (f64, f64),
682  reflection: Reflection,
683  smooth_quadratic_control: (f64, f64),
684  closed: bool,
685}
686
687impl Normalizer {
688  /// Appends the segment, or drops it and returns false when a coordinate overflows `f32`.
689  fn push(&mut self, absolute: bool, segment: Segment) -> bool {
690    let appended_from = self.commands.len();
691    let replaced = self.commands.last().copied();
692
693    self.append(absolute, segment);
694
695    let mut finite = true;
696
697    // A moveto after a moveto replaces it in place, so the last old command is checked too.
698    for command in &self.commands[appended_from.saturating_sub(1)..] {
699      command.map_points(|point| {
700        finite &= point.x.is_finite() && point.y.is_finite();
701        point
702      });
703    }
704
705    if !finite {
706      self.commands.truncate(appended_from);
707
708      if let (Some(replaced), Some(last)) = (replaced, appended_from.checked_sub(1)) {
709        self.commands[last] = replaced;
710      }
711    }
712
713    finite
714  }
715
716  fn append(&mut self, absolute: bool, segment: Segment) {
717    if self.closed && !matches!(segment, Segment::MoveTo(..) | Segment::Close) {
718      self.move_to(self.subpath_start);
719    }
720
721    let (origin_x, origin_y) = if absolute { (0.0, 0.0) } else { self.current };
722    let (current_x, current_y) = self.current;
723
724    match segment {
725      Segment::MoveTo(x, y) => {
726        let (origin_x, origin_y) = match (absolute, self.closed) {
727          (true, _) => (0.0, 0.0),
728          (false, true) => self.subpath_start,
729          (false, false) => self.current,
730        };
731
732        self.move_to((x + origin_x, y + origin_y));
733        self.reflection = Reflection::None;
734      }
735      Segment::LineTo(x, y) => {
736        self.line_to((x + origin_x, y + origin_y));
737        self.reflection = Reflection::None;
738      }
739      Segment::Horizontal(x) => {
740        self.line_to((x + origin_x, current_y));
741        self.reflection = Reflection::None;
742      }
743      Segment::Vertical(y) => {
744        self.line_to((current_x, y + origin_y));
745        self.reflection = Reflection::None;
746      }
747      Segment::Cubic([x1, y1, x2, y2, x, y]) => {
748        let control = (x2 + origin_x, y2 + origin_y);
749        let end = (x + origin_x, y + origin_y);
750
751        self.cubic_to((x1 + origin_x, y1 + origin_y), control, end);
752        self.reflection = Reflection::Cubic { control, end };
753      }
754      Segment::SmoothCubic([x2, y2, x, y]) => {
755        let first = match self.reflection {
756          Reflection::Cubic { control, end } => (end.0 * 2.0 - control.0, end.1 * 2.0 - control.1),
757          _ => self.current,
758        };
759        let control = (x2 + origin_x, y2 + origin_y);
760        let end = (x + origin_x, y + origin_y);
761
762        self.cubic_to(first, control, end);
763        self.reflection = Reflection::Cubic { control, end };
764      }
765      Segment::Quadratic([x1, y1, x, y]) => {
766        let control = (x1 + origin_x, y1 + origin_y);
767        let end = (x + origin_x, y + origin_y);
768
769        self.quadratic_to(control, end);
770        self.reflection = Reflection::Quadratic { control, end };
771      }
772      Segment::SmoothQuadratic(x, y) => {
773        let control = match self.reflection {
774          Reflection::Quadratic { control, end } => {
775            (end.0 * 2.0 - control.0, end.1 * 2.0 - control.1)
776          }
777          Reflection::SmoothQuadratic { end } => (
778            end.0 * 2.0 - self.smooth_quadratic_control.0,
779            end.1 * 2.0 - self.smooth_quadratic_control.1,
780          ),
781          _ => self.current,
782        };
783        let end = (x + origin_x, y + origin_y);
784
785        self.smooth_quadratic_control = control;
786        self.quadratic_to(control, end);
787        self.reflection = Reflection::SmoothQuadratic { end };
788      }
789      Segment::Arc(arc) => {
790        let end = (arc.to.0 + origin_x, arc.to.1 + origin_y);
791
792        self.arc_to(&arc, end);
793        self.reflection = Reflection::None;
794      }
795      Segment::Close => {
796        if !self.closed {
797          self.commands.push(PathCommand::Close);
798        }
799
800        self.current = self.subpath_start;
801        self.closed = true;
802        self.reflection = Reflection::None;
803
804        return;
805      }
806    }
807
808    self.closed = false;
809  }
810
811  /// A moveto right after a moveto replaces it, as tiny-skia's `PathBuilder::move_to`.
812  fn move_to(&mut self, point: (f64, f64)) {
813    let command = PathCommand::MoveTo(single(point));
814
815    if let Some(last @ PathCommand::MoveTo(_)) = self.commands.last_mut() {
816      *last = command;
817    } else {
818      self.commands.push(command);
819    }
820
821    self.current = point;
822    self.subpath_start = point;
823  }
824
825  fn line_to(&mut self, point: (f64, f64)) {
826    self.commands.push(PathCommand::LineTo(single(point)));
827    self.current = point;
828  }
829
830  fn quadratic_to(&mut self, control: (f64, f64), end: (f64, f64)) {
831    self
832      .commands
833      .push(PathCommand::QuadTo(single(control), single(end)));
834    self.current = end;
835  }
836
837  fn cubic_to(&mut self, first: (f64, f64), second: (f64, f64), end: (f64, f64)) {
838    self.commands.push(PathCommand::CubicTo(
839      single(first),
840      single(second),
841      single(end),
842    ));
843    self.current = end;
844  }
845
846  fn arc_to(&mut self, arc: &ArcSegment, end: (f64, f64)) {
847    match arc.cubics(self.current, end) {
848      Some(cubics) => {
849        for [first, second, to] in cubics {
850          self.cubic_to(first, second, to);
851        }
852      }
853      None => self.line_to(end),
854    }
855  }
856}
857
858impl ArcSegment {
859  /// The arc from `from` to `to` as at most four cubics, or none where it is a straight line.
860  /// Blink's `SVGPathNormalizer::DecomposeArcToCubic` (core/svg/svg_path_parser.cc).
861  fn cubics(&self, from: (f64, f64), to: (f64, f64)) -> Option<Vec<[(f64, f64); 3]>> {
862    let angle = self.rotation.to_radians();
863    let (mut rx, mut ry) = (self.radii.0.abs(), self.radii.1.abs());
864
865    if rx == 0.0 || ry == 0.0 || from == to {
866      return None;
867    }
868
869    let mid = ((from.0 - to.0) * 0.5, (from.1 - to.1) * 0.5);
870    let mid = rotated(mid, -angle);
871    let radii_scale = mid.0 * mid.0 / (rx * rx) + mid.1 * mid.1 / (ry * ry);
872
873    if radii_scale > 1.0 {
874      rx *= radii_scale.sqrt();
875      ry *= radii_scale.sqrt();
876    }
877
878    let to_unit_circle = |point| {
879      let (x, y) = rotated(point, -angle);
880
881      (x / rx, y / ry)
882    };
883    let point1 = to_unit_circle(from);
884    let point2 = to_unit_circle(to);
885    let delta = (point2.0 - point1.0, point2.1 - point1.1);
886    let mut scale_factor = (1.0 / (delta.0 * delta.0 + delta.1 * delta.1) - 0.25)
887      .max(0.0)
888      .sqrt()
889      .min(f64::from(f32::MAX));
890
891    if self.sweep == self.large_arc {
892      scale_factor = -scale_factor;
893    }
894
895    let center = (
896      (point1.0 + point2.0) * 0.5 - delta.1 * scale_factor,
897      (point1.1 + point2.1) * 0.5 + delta.0 * scale_factor,
898    );
899    let theta1 = (point1.1 - center.1).atan2(point1.0 - center.0);
900    let theta2 = (point2.1 - center.1).atan2(point2.0 - center.0);
901    let mut sweep = theta2 - theta1;
902
903    if sweep < 0.0 && self.sweep {
904      sweep += TAU;
905    } else if sweep > 0.0 && !self.sweep {
906      sweep -= TAU;
907    }
908
909    if !sweep.is_finite() {
910      return None;
911    }
912
913    // The extra 0.001 keeps a quarter turn that atan2 rounds a little over from becoming two cubics.
914    let segments = (sweep / (FRAC_PI_2 + 0.001)).abs().ceil() as usize;
915    let to_user_space = |(x, y): (f64, f64)| rotated((x * rx, y * ry), angle);
916    let mut cubics = Vec::with_capacity(segments);
917
918    for index in 0..segments {
919      let start = theta1 + index as f64 * sweep / segments as f64;
920      let end = theta1 + (index + 1) as f64 * sweep / segments as f64;
921      let tangent = (8.0 / 6.0) * (0.25 * (end - start)).tan();
922
923      if !tangent.is_finite() {
924        return None;
925      }
926
927      let (sin_start, cos_start) = start.sin_cos();
928      let (sin_end, cos_end) = end.sin_cos();
929      let first = (
930        cos_start - tangent * sin_start + center.0,
931        sin_start + tangent * cos_start + center.1,
932      );
933      let end_point = (cos_end + center.0, sin_end + center.1);
934      let second = (
935        end_point.0 + tangent * sin_end,
936        end_point.1 - tangent * cos_end,
937      );
938
939      cubics.push([
940        to_user_space(first),
941        to_user_space(second),
942        to_user_space(end_point),
943      ]);
944    }
945
946    Some(cubics)
947  }
948}
949
950impl PathData {
951  /// The commands of the clockwise arc of less than half a turn from `from` to `to` on an ellipse
952  /// with radii `rx` and `ry`, as the corners of a `rect` and the sides of an `ellipse` take.
953  #[cfg(feature = "svg")]
954  pub(crate) fn corner_arc(from: (f32, f32), to: (f32, f32), rx: f32, ry: f32) -> Vec<PathCommand> {
955    let point = |(x, y): (f32, f32)| (f64::from(x), f64::from(y));
956    let arc = ArcSegment {
957      radii: (f64::from(rx), f64::from(ry)),
958      rotation: 0.0,
959      large_arc: false,
960      sweep: true,
961      to: point(to),
962    };
963
964    match arc.cubics(point(from), point(to)) {
965      Some(cubics) => cubics
966        .into_iter()
967        .map(|[first, second, to]| PathCommand::CubicTo(single(first), single(second), single(to)))
968        .collect(),
969      None => vec![PathCommand::LineTo(Point::new(to.0, to.1))],
970    }
971  }
972}
973
974/// `point` turned by `angle` radians.
975fn rotated((x, y): (f64, f64), angle: f64) -> (f64, f64) {
976  let (sin, cos) = angle.sin_cos();
977
978  (x * cos - y * sin, x * sin + y * cos)
979}
980
981fn single((x, y): (f64, f64)) -> Point<f32> {
982  Point::new(x as f32, y as f32)
983}
984
985#[cfg(test)]
986mod tests {
987  use super::*;
988
989  /// `Num` as float `Display` prints it, the integer-part zero dropped.
990  fn displayed(value: f32) -> String {
991    if !value.is_finite() {
992      return "0".into();
993    }
994    let value = (value * COORD_FACTOR).round() / COORD_FACTOR;
995    if value == 0.0 {
996      return "0".into();
997    }
998    let text = value.to_string();
999    if let Some(rest) = text.strip_prefix("0.") {
1000      format!(".{rest}")
1001    } else if let Some(rest) = text.strip_prefix("-0.") {
1002      format!("-.{rest}")
1003    } else {
1004      text
1005    }
1006  }
1007
1008  #[test]
1009  fn num_matches_float_display() {
1010    let mut state = 0x2545_F491_4F6C_DD1D_u64;
1011
1012    for index in 0..200_000_u64 {
1013      state ^= state << 13;
1014      state ^= state >> 7;
1015      state ^= state << 17;
1016
1017      let value = match index % 4 {
1018        0 => f32::from_bits(state as u32),
1019        1 => ((state % 2_000_000) as f32 - 1_000_000.0) / 1000.0,
1020        2 => ((state % 200_000_000) as f32 - 100_000_000.0) / 7919.0,
1021        _ => (state as u32 as f32 / u32::MAX as f32 - 0.5) * 4.0,
1022      };
1023
1024      assert_eq!(Num(value).to_string(), displayed(value), "{value:?}");
1025    }
1026    for value in [
1027      f32::MAX,
1028      f32::MIN,
1029      999.9995,
1030      -999.9995,
1031      1000.0,
1032      0.0005,
1033      -0.0004,
1034    ] {
1035      assert_eq!(Num(value).to_string(), displayed(value), "{value:?}");
1036    }
1037  }
1038
1039  fn build(f: impl FnOnce(&mut PathData)) -> String {
1040    let mut path = PathData::with_capacity(0);
1041    f(&mut path);
1042    path.into_string()
1043  }
1044
1045  #[test]
1046  fn drops_separator_only_when_grammar_allows() {
1047    // digit-led number needs a separator; minus and `.`-after-`.` do not.
1048    assert_eq!(
1049      build(|p| {
1050        p.command(b'L');
1051        p.pair(10.0, 10.0);
1052      }),
1053      "L10 10"
1054    );
1055    assert_eq!(
1056      build(|p| {
1057        p.command(b'L');
1058        p.pair(10.0, -5.0);
1059      }),
1060      "L10-5"
1061    );
1062    assert_eq!(
1063      build(|p| {
1064        p.command(b'L');
1065        p.pair(0.5, 0.5);
1066      }),
1067      "L.5.5"
1068    );
1069    // `.`-led after an integer must keep the separator or it would merge.
1070    assert_eq!(
1071      build(|p| {
1072        p.command(b'L');
1073        p.pair(1.0, 0.5);
1074      }),
1075      "L1 .5"
1076    );
1077    assert_eq!(
1078      build(|p| {
1079        p.command(b'L');
1080        p.pair(1.5, 0.5);
1081      }),
1082      "L1.5.5"
1083    );
1084  }
1085
1086  #[test]
1087  fn elides_repeated_and_moveto_implicit_line() {
1088    let path = build(|p| {
1089      p.command(b'M');
1090      p.pair(0.0, 0.0);
1091      p.command(b'L');
1092      p.pair(1.0, 1.0);
1093      p.command(b'L');
1094      p.pair(2.0, 2.0);
1095    });
1096    assert_eq!(path, "M0 0 1 1 2 2");
1097  }
1098
1099  fn pt(x: f32, y: f32) -> Point<f32> {
1100    Point::new(x, y)
1101  }
1102
1103  #[test]
1104  fn path_data_is_relative_with_hv_shorthands() {
1105    let commands = [
1106      PathCommand::MoveTo(pt(10.0, 10.0)),
1107      PathCommand::LineTo(pt(20.0, 10.0)),
1108      PathCommand::LineTo(pt(20.0, 20.0)),
1109      PathCommand::Close,
1110    ];
1111    assert_eq!(path_data(&commands, Affine::IDENTITY), "M10 10h10v10Z");
1112  }
1113
1114  #[test]
1115  fn path_data_uses_smooth_cubic_shorthand() {
1116    // The second cubic's first control is the reflection of the first cubic's
1117    // second control about the join, so it collapses to `s`.
1118    let commands = [
1119      PathCommand::MoveTo(pt(0.0, 0.0)),
1120      PathCommand::CubicTo(pt(0.0, 5.0), pt(5.0, 5.0), pt(5.0, 0.0)),
1121      PathCommand::CubicTo(pt(5.0, -5.0), pt(10.0, -5.0), pt(10.0, 0.0)),
1122    ];
1123    assert_eq!(
1124      path_data(&commands, Affine::IDENTITY),
1125      "M0 0c0 5 5 5 5 0s5-5 5 0"
1126    );
1127  }
1128
1129  #[test]
1130  fn path_data_quantizes_to_two_decimals() {
1131    let commands = [
1132      PathCommand::MoveTo(pt(0.0, 0.0)),
1133      PathCommand::LineTo(pt(1.2345, 6.789)),
1134    ];
1135    assert_eq!(path_data(&commands, Affine::IDENTITY), "M0 0l1.23 6.79");
1136  }
1137
1138  #[test]
1139  fn consecutive_moves_keep_their_letter() {
1140    let commands = [
1141      PathCommand::MoveTo(pt(0.0, 0.0)),
1142      PathCommand::LineTo(pt(10.0, 0.0)),
1143      PathCommand::MoveTo(pt(20.0, 0.0)),
1144      PathCommand::MoveTo(pt(30.0, 5.0)),
1145      PathCommand::LineTo(pt(40.0, 5.0)),
1146    ];
1147    assert_eq!(
1148      path_data(&commands, Affine::IDENTITY),
1149      "M0 0h10m10 0m10 5h10"
1150    );
1151  }
1152
1153  #[test]
1154  fn close_forces_next_command_letter() {
1155    let path = build(|p| {
1156      p.command(b'M');
1157      p.pair(0.0, 0.0);
1158      p.close();
1159      p.command(b'M');
1160      p.pair(1.0, 1.0);
1161    });
1162    assert_eq!(path, "M0 0ZM1 1");
1163  }
1164
1165  fn p(x: f32, y: f32) -> Point<f32> {
1166    Point::new(x, y)
1167  }
1168
1169  fn parsed(text: &str) -> Vec<PathCommand> {
1170    PathData::parse(text).0
1171  }
1172
1173  #[test]
1174  fn a_moveto_followed_by_pairs_continues_as_linetos() {
1175    assert_eq!(
1176      parsed("m 30 40 110 120 -20 -130"),
1177      [
1178        PathCommand::MoveTo(p(30.0, 40.0)),
1179        PathCommand::LineTo(p(140.0, 160.0)),
1180        PathCommand::LineTo(p(120.0, 30.0)),
1181      ]
1182    );
1183  }
1184
1185  #[test]
1186  fn a_command_after_close_starts_at_the_subpath_start() {
1187    assert_eq!(
1188      parsed("M 10 20 L 30 40 Z L 50 60"),
1189      [
1190        PathCommand::MoveTo(p(10.0, 20.0)),
1191        PathCommand::LineTo(p(30.0, 40.0)),
1192        PathCommand::Close,
1193        PathCommand::MoveTo(p(10.0, 20.0)),
1194        PathCommand::LineTo(p(50.0, 60.0)),
1195      ]
1196    );
1197  }
1198
1199  #[test]
1200  fn a_relative_moveto_after_close_is_relative_to_the_subpath_start() {
1201    assert_eq!(
1202      parsed("M 10 10 L 20 20 z m 5 5"),
1203      [
1204        PathCommand::MoveTo(p(10.0, 10.0)),
1205        PathCommand::LineTo(p(20.0, 20.0)),
1206        PathCommand::Close,
1207        PathCommand::MoveTo(p(15.0, 15.0)),
1208      ]
1209    );
1210  }
1211
1212  #[test]
1213  fn repeated_closes_collapse() {
1214    assert_eq!(
1215      parsed("M 10 20 L 30 40 Z Z Z"),
1216      [
1217        PathCommand::MoveTo(p(10.0, 20.0)),
1218        PathCommand::LineTo(p(30.0, 40.0)),
1219        PathCommand::Close,
1220      ]
1221    );
1222  }
1223
1224  #[test]
1225  fn consecutive_movetos_collapse() {
1226    assert_eq!(
1227      parsed("M 10 10 M 20 20 L 30 30"),
1228      [
1229        PathCommand::MoveTo(p(20.0, 20.0)),
1230        PathCommand::LineTo(p(30.0, 30.0)),
1231      ]
1232    );
1233  }
1234
1235  #[test]
1236  fn smooth_curves_reflect_the_previous_control_point() {
1237    assert_eq!(
1238      parsed("M 30 40 C 16 137 171 45 100 90 S 171 45 180 155"),
1239      [
1240        PathCommand::MoveTo(p(30.0, 40.0)),
1241        PathCommand::CubicTo(p(16.0, 137.0), p(171.0, 45.0), p(100.0, 90.0)),
1242        PathCommand::CubicTo(p(29.0, 135.0), p(171.0, 45.0), p(180.0, 155.0)),
1243      ]
1244    );
1245    assert_eq!(
1246      parsed("M 30 40 q 171 45 50 40 t 60 80"),
1247      [
1248        PathCommand::MoveTo(p(30.0, 40.0)),
1249        PathCommand::QuadTo(p(201.0, 85.0), p(80.0, 80.0)),
1250        PathCommand::QuadTo(p(-41.0, 75.0), p(140.0, 160.0)),
1251      ]
1252    );
1253    assert_eq!(
1254      parsed("M 30 40 S 171 45 180 155"),
1255      [
1256        PathCommand::MoveTo(p(30.0, 40.0)),
1257        PathCommand::CubicTo(p(30.0, 40.0), p(171.0, 45.0), p(180.0, 155.0)),
1258      ]
1259    );
1260  }
1261
1262  #[test]
1263  fn arc_flags_need_no_separators() {
1264    let (commands, complete) = PathData::parse("M10-20A5.5.3-4 010-.1");
1265
1266    assert!(complete);
1267    assert!(matches!(commands.first(), Some(PathCommand::MoveTo(_))));
1268    assert!(matches!(commands.last(), Some(PathCommand::CubicTo(..))));
1269    assert_eq!(parsed("M0 0 a1 1 0 00 10 10").len(), 3);
1270  }
1271
1272  #[test]
1273  fn an_arc_with_zero_radii_is_a_line() {
1274    assert_eq!(
1275      parsed("M 0 0 A 0 0 0 0 0 10 10"),
1276      [
1277        PathCommand::MoveTo(p(0.0, 0.0)),
1278        PathCommand::LineTo(p(10.0, 10.0)),
1279      ]
1280    );
1281  }
1282
1283  #[test]
1284  fn numbers_follow_the_svg_grammar() {
1285    assert_eq!(
1286      parsed("M 1e2 .5.5-.5 +1.5e-1 2"),
1287      [
1288        PathCommand::MoveTo(p(100.0, 0.5)),
1289        PathCommand::LineTo(p(0.5, -0.5)),
1290        PathCommand::LineTo(p(0.15, 2.0)),
1291      ]
1292    );
1293  }
1294
1295  #[test]
1296  fn the_commands_before_an_error_are_kept() {
1297    let (commands, complete) = PathData::parse("M 10 10 L 20 20 X 30 30");
1298
1299    assert!(!complete);
1300    assert_eq!(
1301      commands,
1302      [
1303        PathCommand::MoveTo(p(10.0, 10.0)),
1304        PathCommand::LineTo(p(20.0, 20.0)),
1305      ]
1306    );
1307  }
1308
1309  #[test]
1310  fn path_data_must_start_with_a_moveto() {
1311    assert_eq!(PathData::parse("L 10 10"), (Vec::new(), false));
1312    assert_eq!(
1313      PathData::parse("M 0 0 Z 2"),
1314      (
1315        vec![PathCommand::MoveTo(p(0.0, 0.0)), PathCommand::Close],
1316        false
1317      )
1318    );
1319    assert_eq!(PathData::parse(""), (Vec::new(), true));
1320  }
1321
1322  #[test]
1323  fn an_incomplete_number_stops_parsing() {
1324    assert!(!PathData::parse("M 0 0 L 10").1);
1325    assert!(!PathData::parse("M 0 0 L 10 1e").1);
1326  }
1327
1328  #[test]
1329  fn an_arc_is_at_most_four_cubics_whatever_its_radius() {
1330    for radius in ["1", "1e30", "3.4e38"] {
1331      let (commands, complete) = PathData::parse(&format!("M 0 0 A {radius} {radius} 0 1 1 10 10"));
1332
1333      assert!(complete, "{radius}");
1334      assert!(commands.len() <= 5, "{radius}: {}", commands.len());
1335    }
1336
1337    assert_eq!(parsed("M 0 0 A 5 5 0 1 1 0 0.0001").len(), 5);
1338  }
1339
1340  #[test]
1341  fn a_value_that_overflows_f32_is_invalid() {
1342    assert_eq!(
1343      PathData::parse("M 0 0 A 1e39 1 0 0 0 10 10"),
1344      (parsed("M 0 0"), false)
1345    );
1346    assert!(!PathData::parse("M 0 0 L 1e39 0").1);
1347    assert!(!PathData::parse("M 3e38 0 l 3e38 0").1);
1348    assert!(!PathData::parse("M 3e38 0 m 3e38 0").1);
1349  }
1350
1351  #[test]
1352  fn an_arc_flag_takes_spaces_before_its_comma() {
1353    assert!(PathData::parse("M 0 0 A 5 5 0 1 ,0 10 10").1);
1354    assert!(PathData::parse("M 0 0 A 5 5 0 1 , 0 10 10").1);
1355  }
1356}