1use anyhow::{Error, bail};
2use etagere::euclid::{Point2D, Vector2D};
3use lyon_path::geom::{Angle, CubicBezierSegment, QuadraticBezierSegment};
4use lyon_path::math::{Vector, vector};
5use lyon_path::traits::SvgPathBuilder;
6use lyon_path::{ArcFlags, Event, Polygon};
7
8pub use lyon_path::math::Transform;
9pub use lyon_path::{FillRule, LineCap, LineJoin};
10
11use crate::{PathCurve, PathTiles, Pixels, Point, point, px};
12use std::sync::Arc;
13
14pub enum PathStyle {
16 Stroke(StrokeOptions),
18 Fill(FillOptions),
20}
21
22#[derive(Clone, Copy, Debug, PartialEq)]
24pub struct StrokeOptions {
25 pub line_width: f32,
27 pub line_cap: LineCap,
29 pub line_join: LineJoin,
31 pub miter_limit: f32,
34}
35
36impl Default for StrokeOptions {
37 fn default() -> Self {
38 Self {
39 line_width: 1.0,
40 line_cap: LineCap::Butt,
41 line_join: LineJoin::Miter,
42 miter_limit: 4.0,
43 }
44 }
45}
46
47#[derive(Clone, Copy, Debug, PartialEq)]
49pub struct FillOptions {
50 pub fill_rule: FillRule,
52}
53
54impl Default for FillOptions {
55 fn default() -> Self {
56 Self {
57 fill_rule: FillRule::EvenOdd,
58 }
59 }
60}
61
62pub struct PathBuilder {
64 raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>,
65 transform: Option<lyon_path::math::Transform>,
66 pub style: PathStyle,
68 dash_array: Option<Vec<Pixels>>,
69}
70
71impl From<lyon_path::Builder> for PathBuilder {
72 fn from(builder: lyon_path::Builder) -> Self {
73 Self {
74 raw: builder.with_svg(),
75 ..Default::default()
76 }
77 }
78}
79
80impl From<lyon_path::builder::WithSvg<lyon_path::BuilderImpl>> for PathBuilder {
81 fn from(raw: lyon_path::builder::WithSvg<lyon_path::BuilderImpl>) -> Self {
82 Self {
83 raw,
84 ..Default::default()
85 }
86 }
87}
88
89impl From<lyon_path::math::Point> for Point<Pixels> {
90 fn from(p: lyon_path::math::Point) -> Self {
91 point(px(p.x), px(p.y))
92 }
93}
94
95impl From<Point<Pixels>> for lyon_path::math::Point {
96 fn from(p: Point<Pixels>) -> Self {
97 lyon_path::math::point(p.x.0, p.y.0)
98 }
99}
100
101impl From<Point<Pixels>> for Vector {
102 fn from(p: Point<Pixels>) -> Self {
103 vector(p.x.0, p.y.0)
104 }
105}
106
107impl From<Point<Pixels>> for Point2D<f32, Pixels> {
108 fn from(p: Point<Pixels>) -> Self {
109 Point2D::new(p.x.0, p.y.0)
110 }
111}
112
113impl Default for PathBuilder {
114 fn default() -> Self {
115 Self {
116 raw: lyon_path::Path::builder().with_svg(),
117 style: PathStyle::Fill(FillOptions::default()),
118 transform: None,
119 dash_array: None,
120 }
121 }
122}
123
124impl PathBuilder {
125 pub fn stroke(width: Pixels) -> Self {
127 Self {
128 style: PathStyle::Stroke(StrokeOptions {
129 line_width: width.0,
130 ..Default::default()
131 }),
132 ..Self::default()
133 }
134 }
135
136 pub fn fill() -> Self {
138 Self::default()
139 }
140
141 pub fn with_style(self, style: PathStyle) -> Self {
143 Self { style, ..self }
144 }
145
146 pub fn dash_array(mut self, dash_array: &[Pixels]) -> Self {
150 let array = if dash_array.len() % 2 == 1 {
153 let mut new_dash_array = dash_array.to_vec();
154 new_dash_array.extend_from_slice(dash_array);
155 new_dash_array
156 } else {
157 dash_array.to_vec()
158 };
159
160 self.dash_array = Some(array);
161 self
162 }
163
164 #[inline]
166 pub fn move_to(&mut self, to: Point<Pixels>) {
167 self.raw.move_to(to.into());
168 }
169
170 #[inline]
172 pub fn line_to(&mut self, to: Point<Pixels>) {
173 self.raw.line_to(to.into());
174 }
175
176 #[inline]
178 pub fn curve_to(&mut self, to: Point<Pixels>, ctrl: Point<Pixels>) {
179 self.raw.quadratic_bezier_to(ctrl.into(), to.into());
180 }
181
182 #[inline]
185 pub fn cubic_bezier_to(
186 &mut self,
187 to: Point<Pixels>,
188 control_a: Point<Pixels>,
189 control_b: Point<Pixels>,
190 ) {
191 self.raw
192 .cubic_bezier_to(control_a.into(), control_b.into(), to.into());
193 }
194
195 pub fn arc_to(
197 &mut self,
198 radii: Point<Pixels>,
199 x_rotation: Pixels,
200 large_arc: bool,
201 sweep: bool,
202 to: Point<Pixels>,
203 ) {
204 self.raw.arc_to(
205 radii.into(),
206 Angle::degrees(x_rotation.into()),
207 ArcFlags { large_arc, sweep },
208 to.into(),
209 );
210 }
211
212 pub fn relative_arc_to(
214 &mut self,
215 radii: Point<Pixels>,
216 x_rotation: Pixels,
217 large_arc: bool,
218 sweep: bool,
219 to: Point<Pixels>,
220 ) {
221 self.raw.relative_arc_to(
222 radii.into(),
223 Angle::degrees(x_rotation.into()),
224 ArcFlags { large_arc, sweep },
225 to.into(),
226 );
227 }
228
229 pub fn add_polygon(&mut self, points: &[Point<Pixels>], closed: bool) {
231 let points = points.iter().copied().map(|p| p.into()).collect::<Vec<_>>();
232 self.raw.add_polygon(Polygon {
233 points: points.as_ref(),
234 closed,
235 });
236 }
237
238 #[inline]
240 pub fn close(&mut self) {
241 self.raw.close();
242 }
243
244 #[inline]
246 pub fn transform(&mut self, transform: Transform) {
247 self.transform = Some(transform);
248 }
249
250 #[inline]
252 pub fn translate(&mut self, to: Point<Pixels>) {
253 if let Some(transform) = self.transform {
254 self.transform = Some(transform.then_translate(Vector2D::new(to.x.0, to.y.0)));
255 } else {
256 self.transform = Some(Transform::translation(to.x.0, to.y.0))
257 }
258 }
259
260 #[inline]
262 pub fn scale(&mut self, scale: f32) {
263 if let Some(transform) = self.transform {
264 self.transform = Some(transform.then_scale(scale, scale));
265 } else {
266 self.transform = Some(Transform::scale(scale, scale));
267 }
268 }
269
270 #[inline]
274 pub fn rotate(&mut self, angle: f32) {
275 let radians = angle.to_radians();
276 if let Some(transform) = self.transform {
277 self.transform = Some(transform.then_rotate(Angle::radians(radians)));
278 } else {
279 self.transform = Some(Transform::rotation(Angle::radians(radians)));
280 }
281 }
282
283 pub fn build(self) -> Result<Path, Error> {
285 let (curves, fill_rule) = self.outline()?;
286 Ok(Path::from_curves(curves, fill_rule))
287 }
288
289 pub(crate) fn outline(self) -> Result<(Vec<PathCurve>, FillRule), Error> {
291 let path = if let Some(transform) = self.transform {
292 self.raw.build().transformed(&transform)
293 } else {
294 self.raw.build()
295 };
296
297 Ok(match self.style {
298 PathStyle::Stroke(options) => (
299 Self::stroke_outline(&path, &options, self.dash_array.as_deref())?,
300 FillRule::NonZero,
301 ),
302 PathStyle::Fill(options) => (Self::fill_outline(&path)?, options.fill_rule),
303 })
304 }
305
306 fn stroke_outline(
307 path: &lyon_path::Path,
308 options: &StrokeOptions,
309 dash_array: Option<&[Pixels]>,
310 ) -> Result<Vec<PathCurve>, Error> {
311 let outline = skia_path(path)
312 .map(|skia_path| match dash_array {
313 Some(dash_array) => {
314 let array = dash_array.iter().map(|length| length.0).collect();
315 match tiny_skia_path::StrokeDash::new(array, 0.0) {
316 Some(dash) => skia_path
317 .dash(&dash, STROKE_RESOLUTION_SCALE)
318 .unwrap_or(skia_path),
319 None => skia_path,
321 }
322 }
323 None => skia_path,
324 })
325 .and_then(|skia_path| {
326 skia_path.stroke(
327 &tiny_skia_path::Stroke {
328 width: options.line_width,
329 miter_limit: options.miter_limit,
330 line_cap: match options.line_cap {
331 LineCap::Butt => tiny_skia_path::LineCap::Butt,
332 LineCap::Square => tiny_skia_path::LineCap::Square,
333 LineCap::Round => tiny_skia_path::LineCap::Round,
334 },
335 line_join: match options.line_join {
336 LineJoin::Miter => tiny_skia_path::LineJoin::Miter,
337 LineJoin::MiterClip => tiny_skia_path::LineJoin::MiterClip,
338 LineJoin::Round => tiny_skia_path::LineJoin::Round,
339 LineJoin::Bevel => tiny_skia_path::LineJoin::Bevel,
340 },
341 dash: None,
342 },
343 STROKE_RESOLUTION_SCALE,
344 )
345 });
346 let Some(outline) = outline else {
347 return Ok(Vec::new());
348 };
349
350 let mut output = Outline::default();
351 let at = |p: tiny_skia_path::Point| point(p.x, p.y);
352 for segment in outline.segments() {
353 match segment {
354 tiny_skia_path::PathSegment::MoveTo(p) => output.move_to(at(p)),
355 tiny_skia_path::PathSegment::LineTo(p) => output.line_to(at(p)),
356 tiny_skia_path::PathSegment::QuadTo(ctrl, p) => output.curve_to(at(p), at(ctrl)),
357 tiny_skia_path::PathSegment::CubicTo(ctrl1, ctrl2, p) => {
358 output.cubic_to(at(p), at(ctrl1), at(ctrl2))
359 }
360 tiny_skia_path::PathSegment::Close => output.close(),
361 }
362 }
363 output.into_curves()
364 }
365
366 fn fill_outline(path: &lyon_path::Path) -> Result<Vec<PathCurve>, Error> {
368 let mut output = Outline::default();
369 let at = |p: lyon_path::math::Point| point(p.x, p.y);
370 for event in path.iter() {
371 match event {
372 Event::Begin { at: p } => output.move_to(at(p)),
373 Event::Line { to, .. } => output.line_to(at(to)),
374 Event::Quadratic { ctrl, to, .. } => output.curve_to(at(to), at(ctrl)),
375 Event::Cubic {
376 ctrl1, ctrl2, to, ..
377 } => output.cubic_to(at(to), at(ctrl1), at(ctrl2)),
378 Event::End { .. } => output.close(),
379 }
380 }
381 output.into_curves()
382 }
383}
384
385#[derive(Clone, Debug)]
387pub struct Path {
388 curves: Arc<[PathCurve]>,
390 even_odd: bool,
391}
392
393impl Path {
394 pub(crate) fn from_curves(curves: Vec<PathCurve>, fill_rule: FillRule) -> Self {
395 Self {
396 curves: curves.into(),
397 even_odd: matches!(fill_rule, FillRule::EvenOdd),
398 }
399 }
400
401 pub(crate) fn even_odd(&self) -> bool {
402 self.even_odd
403 }
404
405 pub(crate) fn bin(&self, scale: f32) -> PathTiles {
408 crate::path_winding::bin(&self.curves, self.even_odd, scale)
409 }
410}
411
412#[derive(Default)]
414pub(crate) struct Outline {
415 curves: Vec<PathCurve>,
416 start: Point<f32>,
417 current: Point<f32>,
418 non_finite: bool,
419}
420
421impl Outline {
422 fn accepts(&mut self, points: &[Point<f32>]) -> bool {
424 self.non_finite |= !points
425 .iter()
426 .all(|point| point.x.is_finite() && point.y.is_finite());
427 !self.non_finite
428 }
429
430 pub(crate) fn move_to(&mut self, to: Point<f32>) {
432 if !self.accepts(&[to]) {
433 return;
434 }
435 self.close();
436 self.start = to;
437 self.current = to;
438 }
439
440 pub(crate) fn line_to(&mut self, to: Point<f32>) {
441 if self.accepts(&[to]) && to != self.current {
442 self.curves.push(PathCurve::line(self.current, to));
443 self.current = to;
444 }
445 }
446
447 pub(crate) fn curve_to(&mut self, to: Point<f32>, ctrl: Point<f32>) {
448 if !self.accepts(&[to, ctrl]) || (to == self.current && ctrl == self.current) {
449 return;
450 }
451 PathCurve::push_monotone(&mut self.curves, self.current, ctrl, to);
452 self.current = to;
453 }
454
455 pub(crate) fn cubic_to(&mut self, to: Point<f32>, ctrl1: Point<f32>, ctrl2: Point<f32>) {
456 const TOLERANCE: f32 = 0.25;
458 if !self.accepts(&[to, ctrl1, ctrl2]) {
459 return;
460 }
461 let lyon_point = |p: Point<f32>| lyon_path::math::point(p.x, p.y);
462 let cubic = CubicBezierSegment {
463 from: lyon_point(self.current),
464 ctrl1: lyon_point(ctrl1),
465 ctrl2: lyon_point(ctrl2),
466 to: lyon_point(to),
467 };
468 cubic.for_each_quadratic_bezier(TOLERANCE, &mut |quadratic| {
469 self.curve_to(
470 point(quadratic.to.x, quadratic.to.y),
471 point(quadratic.ctrl.x, quadratic.ctrl.y),
472 );
473 });
474 }
475
476 pub(crate) fn close(&mut self) {
478 let start = self.start;
479 self.line_to(start);
480 }
481
482 pub(crate) fn into_curves(mut self) -> Result<Vec<PathCurve>, Error> {
484 if self.non_finite {
485 bail!("path has a non-finite point");
486 }
487 self.close();
488 Ok(self.curves)
489 }
490}
491
492impl PathCurve {
493 fn new(p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>, sign: f32) -> Self {
494 Self {
495 p0,
496 p1,
497 a: point(p0.x - 2.0 * ctrl.x + p1.x, p0.y - 2.0 * ctrl.y + p1.y),
498 b: point(2.0 * (ctrl.x - p0.x), 2.0 * (ctrl.y - p0.y)),
499 sign,
500 pad: 0,
501 }
502 }
503
504 fn line(from: Point<f32>, to: Point<f32>) -> Self {
506 let (p0, p1, sign) = downward(from, to);
507 Self {
508 p0,
509 p1,
510 a: point(0.0, 0.0),
511 b: point(p1.x - p0.x, p1.y - p0.y),
512 sign,
513 pad: 0,
514 }
515 }
516
517 fn push_monotone(curves: &mut Vec<Self>, p0: Point<f32>, ctrl: Point<f32>, p1: Point<f32>) {
519 let curve = QuadraticBezierSegment {
520 from: lyon_path::math::point(p0.x, p0.y),
521 ctrl: lyon_path::math::point(ctrl.x, ctrl.y),
522 to: lyon_path::math::point(p1.x, p1.y),
523 };
524 curve.for_each_monotonic(&mut |monotone| {
527 let from = point(monotone.from.x, monotone.from.y);
528 let to = point(monotone.to.x, monotone.to.y);
529 if from == to {
530 return;
531 }
532 let (p0, p1, sign) = downward(from, to);
534 let ctrl = point(
535 monotone.ctrl.x.clamp(p0.x.min(p1.x), p0.x.max(p1.x)),
536 monotone.ctrl.y.clamp(p0.y, p1.y),
537 );
538 curves.push(Self::new(p0, ctrl, p1, sign));
539 });
540 }
541}
542
543fn downward(from: Point<f32>, to: Point<f32>) -> (Point<f32>, Point<f32>, f32) {
544 if from.y > to.y {
545 (to, from, -1.0)
546 } else {
547 (from, to, 1.0)
548 }
549}
550
551const STROKE_RESOLUTION_SCALE: f32 = 2.0;
557
558fn skia_path(path: &lyon_path::Path) -> Option<tiny_skia_path::Path> {
560 let mut builder = tiny_skia_path::PathBuilder::new();
561 for event in path.iter() {
562 match event {
563 Event::Begin { at } => builder.move_to(at.x, at.y),
564 Event::Line { to, .. } => builder.line_to(to.x, to.y),
565 Event::Quadratic { ctrl, to, .. } => builder.quad_to(ctrl.x, ctrl.y, to.x, to.y),
566 Event::Cubic {
567 ctrl1, ctrl2, to, ..
568 } => builder.cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y),
569 Event::End { close, .. } => {
570 if close {
571 builder.close();
572 }
573 }
574 }
575 }
576 builder.finish()
577}