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