Files
image/image/svg/path_data.sakura
T
2026-11-14 15:42:36 -06:00

91 lines
3.1 KiB
Plaintext

#! Contains SVG's path data, as a `path` element's `d` writes it, read into a
#! path.
module malunal::image::svg;
# Reads SVG's path data into a path, as far as it's written correctly, as SVG
# says to draw a path broken partway.
def parse_path(text: strview): path {
var made := path::new();
var read := numbers::of(text);
var command: u8 = 0;
var control := point {}; # The last curve's second control point, which `S` and `T` reflect.
var curved: u8 = 0; # Whether the last command was a cubic, `C`, or a quadratic, `Q`.
while !read.at_end() {
val byte := read.text[read.at];
if byte.is_alpha {
command = byte;
read.at++;
if command == 'Z' || command == 'z' {
made.close();
curved = 0;
continue;
}
} else if command == 0 {
break;
}
val relative := command >= 'a';
val origin := relative ? made.last : point {};
val upper := command.to_upper;
var next_curved: u8 = 0;
if upper == 'M' {
val to := read.point() else { break; };
made.move_to(offset(to, &origin));
# Pairs after a move's first are lines.
command = relative ? 'l' : 'L';
} else if upper == 'L' {
val to := read.point() else { break; };
made.line_to(offset(to, &origin));
} else if upper == 'H' {
val x := read.next() else { break; };
made.line_to(point { x = relative ? made.last.x + x : x, y = made.last.y });
} else if upper == 'V' {
val y := read.next() else { break; };
made.line_to(point { x = made.last.x, y = relative ? made.last.y + y : y });
} else if upper == 'C' || upper == 'S' {
var first := made.last;
if upper == 'C' {
val given := read.point() else { break; };
first = offset(given, &origin);
} else if curved == 'C' {
first = point { x = 2 * made.last.x - control.x, y = 2 * made.last.y - control.y };
}
val second := read.point() else { break; };
val to := read.point() else { break; };
control = offset(second, &origin);
made.cubic_to(first, control, offset(to, &origin));
next_curved = 'C';
} else if upper == 'Q' || upper == 'T' {
var middle := made.last;
if upper == 'Q' {
val given := read.point() else { break; };
middle = offset(given, &origin);
} else if curved == 'Q' {
middle = point { x = 2 * made.last.x - control.x, y = 2 * made.last.y - control.y };
}
val to := read.point() else { break; };
control = middle;
made.quad_to(middle, offset(to, &origin));
next_curved = 'Q';
} else if upper == 'A' {
val rx := read.next() else { break; };
val ry := read.next() else { break; };
val degrees := read.next() else { break; };
val large := read.flag() else { break; };
val sweep := read.flag() else { break; };
val to := read.point() else { break; };
made.arc_to(rx, ry, degrees, large, sweep, offset(to, &origin));
} else {
break;
}
curved = next_curved;
}
return made;
}
def offset(at: point, by: &point): point {
return point { x = at.x + by.x, y = at.y + by.y };
}