1use std::rc::Rc;
12
13use crate::geometry::{Color, Point, RRectDef, Rect, Transform2D};
14
15#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct Vertex {
18 pub x: f32,
19 pub y: f32,
20 pub color: Color,
21}
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum TextureMode {
33 Mask,
35 Color,
37}
38
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
44pub enum BlendMode {
45 #[default]
47 Normal,
48 Multiply,
50 Screen,
52 Add,
54}
55
56#[derive(Clone, Debug)]
58pub enum PaintCommand {
59 Rect { rect: Rect, color: Color, radius: f32 },
61 TexturedRect {
67 rect: Rect,
68 color: Color,
69 uv: [f32; 4],
70 texture_id: u32,
71 mode: TextureMode,
73 },
74 Triangles { vertices: Vec<Vertex>, indices: Vec<u32> },
79 Text {
87 text: Rc<str>,
90 range: Option<(usize, usize)>,
94 font_size: f32,
95 color: Color,
96 position: Point,
98 max_width: Option<f32>,
100 },
101 BoxShadow {
110 rect: Rect,
111 color: Color,
112 radius: f32,
113 blur_radius: f32,
115 },
116 BackdropBlur { rect: Rect, radius: f32, blur_radius: f32, tint: Color },
122 InsetShadow { rect: Rect, color: Color, radius: f32, blur_radius: f32 },
127 LinearGradient {
129 rect: Rect,
130 start: Point,
132 end: Point,
134 from: Color,
135 to: Color,
136 corner_radius: f32,
137 },
138 RadialGradient { rect: Rect, center: Point, radial_radius: f32, from: Color, to: Color, corner_radius: f32 },
140 MaskRect { rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32 },
146 PushBlendMode(BlendMode),
148 PopBlendMode,
150 PushClip(Rect),
156 PushClipRRect { rect: Rect, radius: f32 },
161 PopClip,
163 PushClipPath { vertices: Vec<Vertex>, indices: Vec<u32> },
169 PopClipPath,
171}
172
173#[derive(Clone, Debug, Default)]
176pub struct PaintList {
177 pub commands: Vec<PaintCommand>,
178 pub pending_textures: Vec<(u32, std::rc::Rc<crate::image::ImageData>)>,
182}
183
184#[derive(Clone, Copy, Debug, Default, PartialEq)]
196pub enum LayerEffect {
197 #[default]
199 None,
200 Transform(Transform2D),
202 Opacity(f32),
204 ClipRRect(RRectDef),
206}
207
208pub mod effect_flags {
216 pub const HAS_TRANSFORM: u32 = 1 << 0;
217 pub const HAS_OPACITY: u32 = 1 << 1;
218 pub const HAS_CLIP: u32 = 1 << 2;
219 pub const HAS_BLUR: u32 = 1 << 3;
221 pub const HAS_DROP_SHADOW: u32 = 1 << 4;
223}
224
225impl PaintList {
226 pub fn new() -> Self {
227 Self { commands: Vec::new(), pending_textures: Vec::new() }
228 }
229
230 pub fn clear(&mut self) {
231 self.commands.clear();
232 self.pending_textures.clear();
233 }
234
235 pub fn push(&mut self, cmd: PaintCommand) {
236 self.commands.push(cmd);
237 }
238
239 pub fn push_texture(&mut self, texture_id: u32, data: std::rc::Rc<crate::image::ImageData>) {
241 self.pending_textures.push((texture_id, data));
242 }
243
244 pub fn extend(&mut self, other: &PaintList) {
246 self.commands.extend(other.commands.iter().cloned());
247 self.pending_textures.extend(other.pending_textures.iter().map(|(id, data)| (*id, std::rc::Rc::clone(data))));
249 }
250
251 pub fn rect(&mut self, rect: Rect, color: Color) {
253 self.commands.push(PaintCommand::Rect { rect, color, radius: 0.0 });
254 }
255
256 pub fn rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
258 self.commands.push(PaintCommand::Rect { rect, color, radius });
259 }
260
261 pub fn text(&mut self, text: impl Into<Rc<str>>, font_size: f32, color: Color, position: Point) {
263 self.commands.push(PaintCommand::Text {
264 text: text.into(),
265 range: None,
266 font_size,
267 color,
268 position,
269 max_width: None,
270 });
271 }
272
273 pub fn text_wrapped(
275 &mut self,
276 text: impl Into<Rc<str>>,
277 font_size: f32,
278 color: Color,
279 position: Point,
280 max_width: Option<f32>,
281 ) {
282 self.commands.push(PaintCommand::Text {
283 text: text.into(),
284 range: None,
285 font_size,
286 color,
287 position,
288 max_width,
289 });
290 }
291
292 pub fn text_span(&mut self, text: &Rc<str>, range: (usize, usize), font_size: f32, color: Color, position: Point) {
297 self.commands.push(PaintCommand::Text {
298 text: Rc::clone(text),
299 range: Some(range),
300 font_size,
301 color,
302 position,
303 max_width: None,
304 });
305 }
306
307 pub fn box_shadow(
320 &mut self,
321 rect: Rect,
322 offset: Point,
323 blur_radius: f32,
324 spread: f32,
325 color: Color,
326 corner_radius: f32,
327 ) {
328 let sh_x = rect.x + offset.x - spread;
330 let sh_y = rect.y + offset.y - spread;
331 let sh_w = (rect.width + spread * 2.0).max(0.0);
332 let sh_h = (rect.height + spread * 2.0).max(0.0);
333 let base_radius = (corner_radius + spread).max(0.0);
335
336 let b = blur_radius.max(0.0);
340 let pad = b * 4.0;
341 let padded = Rect::new(sh_x - pad, sh_y - pad, sh_w + pad * 2.0, sh_h + pad * 2.0);
342
343 self.commands.push(PaintCommand::BoxShadow {
344 rect: padded,
345 color,
346 radius: base_radius, blur_radius: b,
348 });
349 }
350
351 pub fn linear_gradient(
353 &mut self,
354 rect: Rect,
355 start: Point,
356 end: Point,
357 from: Color,
358 to: Color,
359 corner_radius: f32,
360 ) {
361 self.commands.push(PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius });
362 }
363
364 pub fn radial_gradient(
366 &mut self,
367 rect: Rect,
368 center: Point,
369 radial_radius: f32,
370 from: Color,
371 to: Color,
372 corner_radius: f32,
373 ) {
374 self.commands.push(PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius });
375 }
376
377 pub fn mask(&mut self, rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32) {
379 self.commands.push(PaintCommand::MaskRect { rect, texture_id, uv, alpha: alpha.clamp(0.0, 1.0) });
380 }
381
382 pub fn inset_shadow(&mut self, rect: Rect, color: Color, radius: f32, blur_radius: f32) {
384 self.commands.push(PaintCommand::InsetShadow { rect, color, radius, blur_radius: blur_radius.max(0.0) });
385 }
386
387 pub fn backdrop_blur(&mut self, rect: Rect, radius: f32, blur_radius: f32, tint: Color) {
389 self.commands.push(PaintCommand::BackdropBlur {
390 rect,
391 radius: radius.max(0.0),
392 blur_radius: blur_radius.max(0.0),
393 tint,
394 });
395 }
396
397 pub fn push_blend_mode(&mut self, mode: BlendMode) {
399 self.commands.push(PaintCommand::PushBlendMode(mode));
400 }
401
402 pub fn pop_blend_mode(&mut self) {
404 self.commands.push(PaintCommand::PopBlendMode);
405 }
406
407 pub fn push_clip(&mut self, rect: Rect) {
409 self.commands.push(PaintCommand::PushClip(rect));
410 }
411
412 pub fn push_clip_rrect(&mut self, rect: Rect, radius: f32) {
414 self.commands.push(PaintCommand::PushClipRRect { rect, radius });
415 }
416
417 pub fn pop_clip(&mut self) {
419 self.commands.push(PaintCommand::PopClip);
420 }
421
422 pub fn is_empty(&self) -> bool {
423 self.commands.is_empty()
424 }
425 pub fn len(&self) -> usize {
426 self.commands.len()
427 }
428}
429
430#[derive(Clone, Copy, Debug)]
448pub enum PathSeg {
449 Line(f32, f32),
451 Quad { cx: f32, cy: f32, x: f32, y: f32, flat: f32 },
453 Cubic { c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32, flat: f32 },
455}
456
457#[derive(Clone, Debug, Default)]
459struct Contour {
460 start: (f32, f32),
461 segs: Vec<PathSeg>,
462 closed: bool,
463}
464
465impl PathSeg {
466 fn end(&self) -> (f32, f32) {
468 match *self {
469 PathSeg::Line(x, y) => (x, y),
470 PathSeg::Quad { x, y, .. } => (x, y),
471 PathSeg::Cubic { x, y, .. } => (x, y),
472 }
473 }
474
475 fn transform(&mut self, sx: f32, sy: f32, fscale: f32) {
477 match self {
478 PathSeg::Line(x, y) => {
479 *x *= sx;
480 *y *= sy;
481 }
482 PathSeg::Quad { cx, cy, x, y, flat } => {
483 *cx *= sx;
484 *cy *= sy;
485 *x *= sx;
486 *y *= sy;
487 *flat *= fscale;
488 }
489 PathSeg::Cubic { c1x, c1y, c2x, c2y, x, y, flat } => {
490 *c1x *= sx;
491 *c1y *= sy;
492 *c2x *= sx;
493 *c2y *= sy;
494 *x *= sx;
495 *y *= sy;
496 *flat *= fscale;
497 }
498 }
499 }
500}
501
502#[derive(Default, Clone, Debug)]
504pub struct PathBuilder {
505 cx: f32,
507 cy: f32,
508 start: (f32, f32),
510 segs: Vec<PathSeg>,
512 contours: Vec<Contour>,
514}
515
516impl PathBuilder {
517 pub fn new() -> Self {
518 Self::default()
519 }
520
521 pub fn transform(&mut self, sx: f32, sy: f32) {
524 let fscale = sx.abs().max(sy.abs());
525 for c in self.contours.iter_mut() {
526 c.start.0 *= sx;
527 c.start.1 *= sy;
528 for seg in c.segs.iter_mut() {
529 seg.transform(sx, sy, fscale);
530 }
531 }
532 self.start.0 *= sx;
533 self.start.1 *= sy;
534 for seg in self.segs.iter_mut() {
535 seg.transform(sx, sy, fscale);
536 }
537 self.cx *= sx;
538 self.cy *= sy;
539 }
540
541 fn flatten_contour(start: (f32, f32), segs: &[PathSeg], out: &mut Vec<(f32, f32)>) {
543 out.push(start);
544 let (mut x0, mut y0) = start;
545 for seg in segs {
546 match *seg {
547 PathSeg::Line(x, y) => out.push((x, y)),
548 PathSeg::Quad { cx, cy, x, y, flat } => flatten_quad_bezier(x0, y0, cx, cy, x, y, flat, out),
549 PathSeg::Cubic { c1x, c1y, c2x, c2y, x, y, flat } => {
550 flatten_cubic_bezier(x0, y0, c1x, c1y, c2x, c2y, x, y, flat, out)
551 }
552 }
553 x0 = seg.end().0;
554 y0 = seg.end().1;
555 }
556 }
557
558 pub fn move_to(&mut self, x: f32, y: f32) {
559 if !self.segs.is_empty() {
561 let segs = std::mem::take(&mut self.segs);
562 self.contours.push(Contour { start: self.start, segs, closed: false });
563 }
564 self.start = (x, y);
565 self.cx = x;
566 self.cy = y;
567 }
568
569 pub fn line_to(&mut self, x: f32, y: f32) {
570 self.segs.push(PathSeg::Line(x, y));
571 self.cx = x;
572 self.cy = y;
573 }
574
575 pub fn quad_to(&mut self, cx: f32, cy: f32, ex: f32, ey: f32, flat: f32) {
578 self.segs.push(PathSeg::Quad { cx, cy, x: ex, y: ey, flat });
579 self.cx = ex;
580 self.cy = ey;
581 }
582
583 #[allow(clippy::too_many_arguments)]
585 pub fn cubic_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, ex: f32, ey: f32, flat: f32) {
586 self.segs.push(PathSeg::Cubic { c1x, c1y, c2x, c2y, x: ex, y: ey, flat });
587 self.cx = ex;
588 self.cy = ey;
589 }
590
591 pub fn arc_to(&mut self, cx: f32, cy: f32, r: f32, start_angle: f32, end_angle: f32, num_segments: u32) {
598 if r <= 0.0 {
599 return;
600 }
601 let sweep = end_angle - start_angle;
602 let sweep = if sweep.abs() >= std::f32::consts::TAU { sweep * 0.999 } else { sweep };
604
605 let segs = (((sweep.abs() / std::f32::consts::FRAC_PI_2).ceil()) as u32).clamp(1, num_segments.max(1));
610 let step = sweep / segs as f32;
611 let flat = (r * step).abs() * 0.05;
612
613 let (sx, sy) = (cx + r * start_angle.cos(), cy + r * start_angle.sin());
618 let dcx = sx - self.cx;
619 let dcy = sy - self.cy;
620 if dcx * dcx + dcy * dcy > 1e-12 {
621 self.segs.push(PathSeg::Line(sx, sy));
622 self.cx = sx;
623 self.cy = sy;
624 }
625
626 let k = (4.0 / 3.0) * (step / 4.0).tan() * r; let mut a0 = start_angle;
628 for _ in 0..segs {
629 let a1 = a0 + step;
630 let (x0, y0) = (cx + r * a0.cos(), cy + r * a0.sin());
631 let (x1, y1) = (cx + r * a1.cos(), cy + r * a1.sin());
632 let c1x = x0 - k * a0.sin();
634 let c1y = y0 + k * a0.cos();
635 let c2x = x1 + k * a1.sin();
636 let c2y = y1 - k * a1.cos();
637 self.segs.push(PathSeg::Cubic { c1x, c1y, c2x, c2y, x: x1, y: y1, flat });
638 self.cx = x1;
639 self.cy = y1;
640 a0 = a1;
641 }
642 }
643
644 pub fn close(&mut self) {
645 if !self.segs.is_empty() {
646 let segs = std::mem::take(&mut self.segs);
647 self.contours.push(Contour { start: self.start, segs, closed: true });
649 }
650 }
651
652 pub fn paths(&self) -> Vec<Vec<(f32, f32)>> {
655 let mut out = Vec::with_capacity(self.contours.len());
656 for c in &self.contours {
657 let mut pts = Vec::new();
658 Self::flatten_contour(c.start, &c.segs, &mut pts);
659 if pts.first() == pts.last() && pts.len() > 1 {
660 pts.pop();
661 }
662 if pts.len() >= 2 {
663 out.push(pts);
664 }
665 }
666 if !self.segs.is_empty() {
668 let mut pts = Vec::new();
669 Self::flatten_contour(self.start, &self.segs, &mut pts);
670 if pts.first() == pts.last() && pts.len() > 1 {
671 pts.pop();
672 }
673 if pts.len() >= 2 {
674 out.push(pts);
675 }
676 }
677 out
678 }
679
680 pub fn curve_contours(&self) -> Vec<((f32, f32), Vec<PathSeg>, bool)> {
686 let mut out = Vec::with_capacity(self.contours.len() + 1);
687 for c in &self.contours {
688 out.push((c.start, c.segs.clone(), c.closed));
689 }
690 if !self.segs.is_empty() {
691 out.push((self.start, self.segs.clone(), false));
692 }
693 out
694 }
695
696 pub fn paths_with_closed(&self) -> Vec<(Vec<(f32, f32)>, bool)> {
701 let mut out = Vec::with_capacity(self.contours.len() + 1);
702 for c in &self.contours {
703 let mut pts = Vec::new();
704 Self::flatten_contour(c.start, &c.segs, &mut pts);
705 if pts.first() == pts.last() && pts.len() > 1 {
706 pts.pop();
707 }
708 if pts.len() >= 2 {
709 out.push((pts, c.closed));
710 }
711 }
712 if !self.segs.is_empty() {
713 let mut pts = Vec::new();
714 Self::flatten_contour(self.start, &self.segs, &mut pts);
715 if pts.first() == pts.last() && pts.len() > 1 {
716 pts.pop();
717 }
718 if pts.len() >= 2 {
719 out.push((pts, false));
720 }
721 }
722 out
723 }
724
725 pub fn fill(self, color: Color, list: &mut PaintList) {
728 if self.contours.is_empty() && self.segs.is_empty() {
729 return;
730 }
731 let mut clean_contours: Vec<Vec<(f32, f32)>> = Vec::with_capacity(self.contours.len());
733 for c in self.contours.iter() {
734 let mut pts = Vec::new();
735 Self::flatten_contour(c.start, &c.segs, &mut pts);
736 if pts.first() == pts.last() && pts.len() > 1 {
737 pts.pop();
738 }
739 if pts.len() >= 3 {
740 clean_contours.push(pts);
741 }
742 }
743 if clean_contours.is_empty() {
744 return;
745 }
746
747 let mut flat: Vec<(f32, f32)> = Vec::new();
749 let mut hole_offsets: Vec<usize> = Vec::new();
750 let mut first = true;
751 for contour in clean_contours.iter() {
752 if !first {
753 hole_offsets.push(flat.len());
754 }
755 first = false;
756 for &p in contour {
757 flat.push(p);
758 }
759 }
760 let (tri_points, indices) = earcut(&flat, if hole_offsets.is_empty() { None } else { Some(&hole_offsets) });
764 if indices.len() < 3 {
765 return;
766 }
767 let vertices: Vec<Vertex> = tri_points.iter().map(|&(x, y)| Vertex { x, y, color }).collect();
768 list.push(PaintCommand::Triangles { vertices, indices });
769 }
770}
771
772#[allow(dead_code)]
777const MAX_FLATTEN_DEPTH: u32 = 10;
778
779#[allow(clippy::too_many_arguments)]
780fn flatten_quad_bezier(x0: f32, y0: f32, cx: f32, cy: f32, ex: f32, ey: f32, flat: f32, out: &mut Vec<(f32, f32)>) {
781 let dx = ex - x0;
783 let dy = ey - y0;
784 let len_sq = dx * dx + dy * dy;
785 if len_sq < 1e-6 {
786 out.push((ex, ey));
787 return;
788 }
789 let cross = dx * (cy - y0) - dy * (cx - x0);
791 let dist = (cross / len_sq.sqrt().max(1e-6)).abs();
792 if dist < flat {
793 out.push((ex, ey));
794 return;
795 }
796 let mx0 = (x0 + cx) / 2.0;
798 let my0 = (y0 + cy) / 2.0;
799 let mx1 = (cx + ex) / 2.0;
800 let my1 = (cy + ey) / 2.0;
801 let mx = (mx0 + mx1) / 2.0;
802 let my = (my0 + my1) / 2.0;
803 flatten_quad_bezier(x0, y0, mx0, my0, mx, my, flat, out);
804 flatten_quad_bezier(mx, my, mx1, my1, ex, ey, flat, out);
805}
806
807#[allow(dead_code, clippy::too_many_arguments)]
809fn flatten_cubic_bezier(
810 x0: f32,
811 y0: f32,
812 x1: f32,
813 y1: f32,
814 x2: f32,
815 y2: f32,
816 x3: f32,
817 y3: f32,
818 flat: f32,
819 out: &mut Vec<(f32, f32)>,
820) {
821 let dx = x3 - x0;
823 let dy = y3 - y0;
824 let len = (dx * dx + dy * dy).sqrt().max(1e-6);
825 let d1 = (dx * (y1 - y0) - dy * (x1 - x0)).abs() / len;
826 let d2 = (dx * (y2 - y0) - dy * (x2 - x0)).abs() / len;
827 if d1.max(d2) < flat {
828 out.push((x3, y3));
829 return;
830 }
831 let (mx01x, mx01y) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
832 let (mx12x, mx12y) = ((x1 + x2) / 2.0, (y1 + y2) / 2.0);
833 let (mx23x, mx23y) = ((x2 + x3) / 2.0, (y2 + y3) / 2.0);
834 let (mxx, mxy) = ((mx01x + mx12x) / 2.0, (mx01y + mx12y) / 2.0);
835 let (myy, myz) = ((mx12x + mx23x) / 2.0, (mx12y + mx23y) / 2.0);
836 let (midx, midy) = ((mxx + myy) / 2.0, (mxy + myz) / 2.0);
837 flatten_cubic_bezier(x0, y0, mx01x, mx01y, mxx, mxy, midx, midy, flat, out);
838 flatten_cubic_bezier(midx, midy, myy, myz, mx23x, mx23y, x3, y3, flat, out);
839}
840
841fn earcut(points: &[(f32, f32)], hole_offsets: Option<&[usize]>) -> (Vec<(f32, f32)>, Vec<u32>) {
847 let n = points.len();
848 if n < 3 {
849 return (Vec::new(), Vec::new());
850 }
851 if hole_offsets.is_none() {
853 return (points.to_vec(), earcut_single(points));
854 }
855 let hole_offsets = hole_offsets.unwrap();
858 let mut merged: Vec<(f32, f32)> = Vec::with_capacity(n + hole_offsets.len());
859 let first_end = hole_offsets.first().copied().unwrap_or(n);
861 merged.extend_from_slice(&points[0..first_end]);
862 let mut contour_start = first_end;
864 for &end_idx in hole_offsets.iter().skip(1) {
865 let hole = &points[contour_start..end_idx];
866 bridge_hole(&mut merged, hole);
867 contour_start = end_idx;
868 }
869 if contour_start < n {
870 let last = &points[contour_start..n];
871 bridge_hole(&mut merged, last);
872 }
873 let indices = earcut_single(&merged);
874 (merged, indices)
875}
876
877fn bridge_hole(outer: &mut Vec<(f32, f32)>, hole: &[(f32, f32)]) {
879 if hole.is_empty() {
880 return;
881 }
882 let mut hole = hole.to_vec();
884 let outer_ccw = area2(outer) > 0.0;
885 let hole_ccw = area2(&hole) > 0.0;
886 if hole_ccw == outer_ccw {
887 hole.reverse();
888 }
889 let hole_pt = hole[0];
891 let mut best_i = 0usize;
892 let mut best_d = f32::INFINITY;
893 for (i, &p) in outer.iter().enumerate() {
894 let d = (p.0 - hole_pt.0).powi(2) + (p.1 - hole_pt.1).powi(2);
895 if d < best_d {
896 best_d = d;
897 best_i = i;
898 }
899 }
900 let insert_pos = best_i + 1;
901 let skip_last = if hole.first() == hole.last() { hole.len() - 1 } else { hole.len() };
902 let bridge = outer[best_i];
903 outer.insert(insert_pos, bridge);
907 outer.splice(insert_pos + 1..insert_pos + 1, hole[..skip_last].iter().copied());
908 let close_pos = insert_pos + 1 + skip_last;
909 if let Some(&first) = hole.first() {
910 outer.insert(close_pos, first);
911 outer.insert(close_pos + 1, bridge);
912 }
913}
914
915fn earcut_single(points: &[(f32, f32)]) -> Vec<u32> {
917 let n = points.len();
918 let points = if points.first() == points.last() { &points[..n - 1] } else { points };
920 let n = points.len();
921 if n < 3 {
922 return Vec::new();
923 }
924
925 let mut result = Vec::with_capacity((n - 2) * 3);
926 let mut active: Vec<usize> = (0..n).collect();
928 let ccw = area2(points) > 0.0;
930
931 let mut safety = n * n; while active.len() >= 3 && safety > 0 {
934 safety -= 1;
935 if active.len() == 3 {
936 let (a, b, c) = (active[0], active[1], active[2]);
940 let (ax, ay) = points[a];
941 let (bx, by) = points[b];
942 let (cx, cy) = points[c];
943 let cross = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
944 if cross.abs() > 1e-6 {
945 result.push(a as u32);
946 result.push(b as u32);
947 result.push(c as u32);
948 }
949 break;
950 }
951 let m = active.len();
952 let mut found = None;
953 for j in 0..m {
954 let prev = active[(j + m - 1) % m];
955 let curr = active[j];
956 let next = active[(j + 1) % m];
957 if is_ear(points, prev, curr, next, ccw) {
958 found = Some(j);
959 break;
960 }
961 }
962 match found {
963 Some(j) => {
964 let prev = active[(j + m - 1) % m];
965 let curr = active[j];
966 let next = active[(j + 1) % m];
967 result.push(prev as u32);
968 result.push(curr as u32);
969 result.push(next as u32);
970 active.remove(j);
971 }
972 None => {
973 return fan_triangulation(points);
975 }
976 }
977 }
978 if result.is_empty() {
979 fan_triangulation(points)
980 } else {
981 result
982 }
983}
984
985fn area2(points: &[(f32, f32)]) -> f32 {
986 let mut a = 0.0f32;
987 for w in points.windows(2) {
988 a += w[0].0 * w[1].1 - w[1].0 * w[0].1;
989 }
990 if points.len() >= 2 {
991 a += points.last().unwrap().0 * points[0].1 - points[0].0 * points.last().unwrap().1;
992 }
993 a
994}
995
996fn is_ear(points: &[(f32, f32)], a: usize, b: usize, c: usize, ccw: bool) -> bool {
997 let (ax, ay) = points[a];
998 let (bx, by) = points[b];
999 let (cx, cy) = points[c];
1000 let abc_cross = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
1003 if (abc_cross > 0.0) != ccw {
1004 return false;
1005 }
1006 for (i, &(px, py)) in points.iter().enumerate() {
1008 if i == a || i == b || i == c {
1009 continue;
1010 }
1011 if point_in_triangle(px, py, ax, ay, bx, by, cx, cy) {
1012 return false;
1013 }
1014 }
1015 true
1016}
1017
1018#[allow(clippy::too_many_arguments)]
1019fn point_in_triangle(px: f32, py: f32, ax: f32, ay: f32, bx: f32, by: f32, cx: f32, cy: f32) -> bool {
1020 let v0x = cx - ax;
1021 let v0y = cy - ay;
1022 let v1x = bx - ax;
1023 let v1y = by - ay;
1024 let v2x = px - ax;
1025 let v2y = py - ay;
1026
1027 let dot00 = v0x * v0x + v0y * v0y;
1028 let dot01 = v0x * v1x + v0y * v1y;
1029 let dot02 = v0x * v2x + v0y * v2y;
1030 let dot11 = v1x * v1x + v1y * v1y;
1031 let dot12 = v1x * v2x + v1y * v2y;
1032
1033 let inv_denom = 1.0 / (dot00 * dot11 - dot01 * dot01).max(1e-9);
1034 let u = (dot11 * dot02 - dot01 * dot12) * inv_denom;
1035 let v = (dot00 * dot12 - dot01 * dot02) * inv_denom;
1036 const EPS: f32 = 1e-6;
1039 u > EPS && v > EPS && (u + v) < 1.0 - EPS
1040}
1041
1042fn fan_triangulation(points: &[(f32, f32)]) -> Vec<u32> {
1044 let mut result = Vec::new();
1045 if points.len() < 3 {
1046 return result;
1047 }
1048 let base = points[0];
1049 for i in 2..points.len() {
1051 let mut ok = true;
1053 for j in 1..points.len() {
1054 if j == i || j == 0 {
1055 continue;
1056 }
1057 if point_in_triangle(
1058 points[j].0,
1059 points[j].1,
1060 base.0,
1061 base.1,
1062 points[1].0,
1063 points[1].1,
1064 points[i].0,
1065 points[i].1,
1066 ) {
1067 ok = false;
1068 break;
1069 }
1070 }
1071 if ok {
1072 result.push(0u32);
1073 result.push(1u32);
1074 result.push(i as u32);
1075 }
1076 }
1077 if result.len() < 3 && points.len() >= 3 {
1079 let n = points.len() as u32;
1080 for i in 1..n - 1 {
1081 result.push(0);
1082 result.push(i);
1083 result.push(i + 1);
1084 }
1085 }
1086 result
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091 use super::*;
1092 use crate::Color;
1093
1094 #[test]
1095 fn path_builder_triangulates_square() {
1096 let mut pb = PathBuilder::new();
1097 pb.move_to(0.0, 0.0);
1098 pb.line_to(100.0, 0.0);
1099 pb.line_to(100.0, 100.0);
1100 pb.line_to(0.0, 100.0);
1101 pb.close();
1102 let mut list = PaintList::new();
1103 pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
1104 assert_eq!(list.commands.len(), 1);
1105 if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1106 assert_eq!(vertices.len(), 4);
1108 assert_eq!(indices.len(), 6);
1109 } else {
1110 panic!("expected Triangles");
1111 }
1112 }
1113
1114 #[test]
1115 fn path_builder_quadbezier_flattens() {
1116 let mut pb = PathBuilder::new();
1117 pb.move_to(0.0, 50.0);
1118 pb.quad_to(50.0, 0.0, 100.0, 50.0, 0.5);
1119 pb.quad_to(50.0, 100.0, 0.0, 50.0, 0.5);
1120 pb.close();
1121 let mut list = PaintList::new();
1122 pb.fill(Color::rgb(0.0, 1.0, 0.0), &mut list);
1123 assert_eq!(list.commands.len(), 1);
1124 if let PaintCommand::Triangles { indices, .. } = &list.commands[0] {
1125 assert!(indices.len() >= 6, "bezier triangulation should produce >= 6 indices, got {}", indices.len());
1126 }
1127 }
1128
1129 #[test]
1130 fn path_builder_arc_to_produces_points() {
1131 let mut pb = PathBuilder::new();
1132 pb.move_to(100.0, 100.0);
1134 pb.arc_to(100.0, 100.0, 50.0, 0.0, std::f32::consts::FRAC_PI_2, 16);
1135 pb.close();
1136 let mut list = PaintList::new();
1137 pb.fill(Color::WHITE, &mut list);
1138
1139 if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1140 assert!(vertices.len() >= 4, "arc + close → 至少 4 vertices");
1141 assert!(indices.len() >= 6, "earcut → 至少 1 triangle(3 indices)");
1142 for v in vertices {
1144 let dx = v.x - 100.0;
1145 let dy = v.y - 100.0;
1146 let d = (dx * dx + dy * dy).sqrt();
1147 assert!((d - 50.0).abs() < 1.0 || d < 1.0, "vertex ({}, {}) should be at r≈50 or center", v.x, v.y);
1148 }
1149 }
1150 }
1151
1152 #[test]
1153 fn path_builder_annulus_sector_triangulates() {
1154 let cx = 100.0;
1156 let cy = 100.0;
1157 let outer_r = 80.0;
1158 let inner_r = 60.0;
1159 let start_a = -std::f32::consts::FRAC_PI_2;
1160 let end_a = start_a + std::f32::consts::TAU * 0.75; let segs = 32u32;
1162
1163 let mut pb = PathBuilder::new();
1164 pb.move_to(cx + outer_r * start_a.cos(), cy + outer_r * start_a.sin());
1165 pb.arc_to(cx, cy, outer_r, start_a, end_a, segs);
1166 pb.line_to(cx + inner_r * end_a.cos(), cy + inner_r * end_a.sin());
1167 pb.arc_to(cx, cy, inner_r, end_a, start_a, segs);
1168 pb.close();
1169
1170 let mut list = PaintList::new();
1171 pb.fill(Color::rgb(0.2, 0.6, 1.0), &mut list);
1172
1173 if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1174 assert!(vertices.len() >= 20, "annulus sector should have many vertices, got {}", vertices.len());
1176 assert!(indices.len() >= 6, "should produce triangles");
1177
1178 for v in vertices {
1180 let dx = v.x - cx;
1181 let dy = v.y - cy;
1182 let d = (dx * dx + dy * dy).sqrt();
1183 let on_outer = (d - outer_r).abs() < 1.0;
1184 let on_inner = (d - inner_r).abs() < 1.0;
1185 let on_radial = v.y == cy; assert!(
1187 on_outer || on_inner || on_radial,
1188 "vertex ({}, {}) d={} not on inner/outer/radial",
1189 v.x,
1190 v.y,
1191 d
1192 );
1193 }
1194 }
1195 }
1196
1197 #[test]
1198 fn box_shadow_pads_four_sigma_and_shrinks_radius_on_negative_spread() {
1199 let mut list = PaintList::new();
1200 list.box_shadow(Rect::new(10.0, 20.0, 100.0, 50.0), Point::new(2.0, 3.0), 5.0, 1.0, Color::BLACK, 8.0);
1201 match &list.commands[0] {
1202 PaintCommand::BoxShadow { rect, radius, blur_radius, .. } => {
1203 assert_eq!(*rect, Rect::new(-9.0, 2.0, 142.0, 92.0));
1205 assert_eq!(*radius, 9.0, "正 spread 圆角增大");
1206 assert_eq!(*blur_radius, 5.0);
1207 }
1208 other => panic!("expected BoxShadow, got {other:?}"),
1209 }
1210
1211 let mut list = PaintList::new();
1212 list.box_shadow(Rect::new(0.0, 0.0, 100.0, 50.0), Point::ZERO, 0.0, -4.0, Color::BLACK, 10.0);
1213 match &list.commands[0] {
1214 PaintCommand::BoxShadow { rect, radius, .. } => {
1215 assert_eq!(*rect, Rect::new(4.0, 4.0, 92.0, 42.0));
1216 assert_eq!(*radius, 6.0, "负 spread 圆角应收缩");
1217 }
1218 other => panic!("expected BoxShadow, got {other:?}"),
1219 }
1220 }
1221
1222 #[test]
1223 fn path_builder_empty_nop() {
1224 let pb = PathBuilder::new();
1225 let mut list = PaintList::new();
1226 pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
1227 assert!(list.is_empty());
1228 }
1229
1230 #[test]
1231 fn earcut_simple_triangle() {
1232 let pts = vec![(0.0, 0.0), (10.0, 0.0), (5.0, 10.0), (0.0, 0.0)];
1233 let (points, indices) = earcut(&pts, None);
1234 assert_eq!(indices.len(), 3);
1236 let unique: std::collections::HashSet<&u32> = indices.iter().collect();
1237 assert_eq!(unique.len(), 3); assert!(indices.iter().all(|&i| (i as usize) < points.len()));
1240 }
1241
1242 fn tri_area_sum(points: &[(f32, f32)], indices: &[u32]) -> f32 {
1243 let mut area = 0.0;
1244 for t in indices.as_chunks::<3>().0 {
1245 let (ax, ay) = points[t[0] as usize];
1246 let (bx, by) = points[t[1] as usize];
1247 let (cx, cy) = points[t[2] as usize];
1248 area += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs() * 0.5;
1249 }
1250 area
1251 }
1252
1253 #[test]
1255 fn earcut_concave_polygon_area_matches() {
1256 let pts = vec![(0.0, 0.0), (60.0, 0.0), (60.0, 20.0), (20.0, 20.0), (20.0, 60.0), (0.0, 60.0)];
1258 let (points, indices) = earcut(&pts, None);
1259 assert_eq!(indices.len(), 12, "6 顶点凹多边形 → 4 个三角形");
1260 assert!(indices.iter().all(|&i| (i as usize) < points.len()));
1261 let expected = area2(&pts).abs() * 0.5;
1262 let got = tri_area_sum(&points, &indices);
1263 assert!((got - expected).abs() < 0.5, "凹多边形面积: expected={expected}, got={got}");
1264 }
1265
1266 #[test]
1268 fn earcut_donut_hole_area_subtracted() {
1269 let outer = vec![(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
1270 let hole = vec![(25.0, 25.0), (75.0, 25.0), (75.0, 75.0), (25.0, 75.0)];
1271 let mut pts = outer.clone();
1272 pts.extend_from_slice(&hole);
1273 let (points, indices) = earcut(&pts, Some(&[outer.len()]));
1274 assert!(!indices.is_empty());
1275 assert!(indices.iter().all(|&i| (i as usize) < points.len()), "索引不得越界");
1276 let got = tri_area_sum(&points, &indices);
1277 let expected = 100.0 * 100.0 - 50.0 * 50.0;
1278 assert!((got - expected).abs() < 1.0, "带洞面积: expected={expected}, got={got}");
1279 }
1280
1281 #[test]
1285 fn fill_multi_contour_indices_in_range() {
1286 let mut pb = PathBuilder::new();
1287 pb.move_to(0.0, 0.0);
1289 pb.line_to(100.0, 0.0);
1290 pb.line_to(100.0, 100.0);
1291 pb.line_to(0.0, 100.0);
1292 pb.close();
1293 pb.move_to(40.0, 40.0);
1295 pb.line_to(60.0, 40.0);
1296 pb.line_to(50.0, 60.0);
1297 pb.close();
1298 let mut list = PaintList::new();
1299 pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
1300 assert_eq!(list.commands.len(), 1);
1301 if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1302 assert!(
1303 indices.iter().all(|&i| (i as usize) < vertices.len()),
1304 "索引 {} 越界(vertices.len={})",
1305 indices.iter().max().unwrap(),
1306 vertices.len()
1307 );
1308 } else {
1309 panic!("expected Triangles");
1310 }
1311 }
1312}