use std::rc::Rc;
use crate::geometry::{Color, Point, RRectDef, Rect, Transform2D};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Vertex {
pub x: f32,
pub y: f32,
pub color: Color,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextureMode {
Mask,
Color,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BlendMode {
#[default]
Normal,
Multiply,
Screen,
Add,
}
#[derive(Clone, Debug)]
pub enum PaintCommand {
Rect { rect: Rect, color: Color, radius: f32 },
TexturedRect {
rect: Rect,
color: Color,
uv: [f32; 4],
texture_id: u32,
mode: TextureMode,
},
Triangles { vertices: Vec<Vertex>, indices: Vec<u32> },
Text {
text: Rc<str>,
range: Option<(usize, usize)>,
font_size: f32,
color: Color,
position: Point,
max_width: Option<f32>,
},
BoxShadow {
rect: Rect,
color: Color,
radius: f32,
blur_radius: f32,
},
BackdropBlur { rect: Rect, radius: f32, blur_radius: f32, tint: Color },
InsetShadow { rect: Rect, color: Color, radius: f32, blur_radius: f32 },
LinearGradient {
rect: Rect,
start: Point,
end: Point,
from: Color,
to: Color,
corner_radius: f32,
},
RadialGradient { rect: Rect, center: Point, radial_radius: f32, from: Color, to: Color, corner_radius: f32 },
MaskRect { rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32 },
PushBlendMode(BlendMode),
PopBlendMode,
PushClip(Rect),
PushClipRRect { rect: Rect, radius: f32 },
PopClip,
PushClipPath { vertices: Vec<Vertex>, indices: Vec<u32> },
PopClipPath,
}
#[derive(Clone, Debug, Default)]
pub struct PaintList {
pub commands: Vec<PaintCommand>,
pub pending_textures: Vec<(u32, std::rc::Rc<crate::image::ImageData>)>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum LayerEffect {
#[default]
None,
Transform(Transform2D),
Opacity(f32),
ClipRRect(RRectDef),
}
pub mod effect_flags {
pub const HAS_TRANSFORM: u32 = 1 << 0;
pub const HAS_OPACITY: u32 = 1 << 1;
pub const HAS_CLIP: u32 = 1 << 2;
pub const HAS_BLUR: u32 = 1 << 3;
pub const HAS_DROP_SHADOW: u32 = 1 << 4;
}
impl PaintList {
pub fn new() -> Self {
Self { commands: Vec::new(), pending_textures: Vec::new() }
}
pub fn clear(&mut self) {
self.commands.clear();
self.pending_textures.clear();
}
pub fn push(&mut self, cmd: PaintCommand) {
self.commands.push(cmd);
}
pub fn push_texture(&mut self, texture_id: u32, data: std::rc::Rc<crate::image::ImageData>) {
self.pending_textures.push((texture_id, data));
}
pub fn extend(&mut self, other: &PaintList) {
self.commands.extend(other.commands.iter().cloned());
self.pending_textures.extend(other.pending_textures.iter().map(|(id, data)| (*id, std::rc::Rc::clone(data))));
}
pub fn rect(&mut self, rect: Rect, color: Color) {
self.commands.push(PaintCommand::Rect { rect, color, radius: 0.0 });
}
pub fn rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
self.commands.push(PaintCommand::Rect { rect, color, radius });
}
pub fn text(&mut self, text: impl Into<Rc<str>>, font_size: f32, color: Color, position: Point) {
self.commands.push(PaintCommand::Text {
text: text.into(),
range: None,
font_size,
color,
position,
max_width: None,
});
}
pub fn text_wrapped(
&mut self,
text: impl Into<Rc<str>>,
font_size: f32,
color: Color,
position: Point,
max_width: Option<f32>,
) {
self.commands.push(PaintCommand::Text {
text: text.into(),
range: None,
font_size,
color,
position,
max_width,
});
}
pub fn text_span(&mut self, text: &Rc<str>, range: (usize, usize), font_size: f32, color: Color, position: Point) {
self.commands.push(PaintCommand::Text {
text: Rc::clone(text),
range: Some(range),
font_size,
color,
position,
max_width: None,
});
}
pub fn box_shadow(
&mut self,
rect: Rect,
offset: Point,
blur_radius: f32,
spread: f32,
color: Color,
corner_radius: f32,
) {
let sh_x = rect.x + offset.x - spread;
let sh_y = rect.y + offset.y - spread;
let sh_w = (rect.width + spread * 2.0).max(0.0);
let sh_h = (rect.height + spread * 2.0).max(0.0);
let base_radius = (corner_radius + spread).max(0.0);
let b = blur_radius.max(0.0);
let pad = b * 4.0;
let padded = Rect::new(sh_x - pad, sh_y - pad, sh_w + pad * 2.0, sh_h + pad * 2.0);
self.commands.push(PaintCommand::BoxShadow {
rect: padded,
color,
radius: base_radius, blur_radius: b,
});
}
pub fn linear_gradient(
&mut self,
rect: Rect,
start: Point,
end: Point,
from: Color,
to: Color,
corner_radius: f32,
) {
self.commands.push(PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius });
}
pub fn radial_gradient(
&mut self,
rect: Rect,
center: Point,
radial_radius: f32,
from: Color,
to: Color,
corner_radius: f32,
) {
self.commands.push(PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius });
}
pub fn mask(&mut self, rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32) {
self.commands.push(PaintCommand::MaskRect { rect, texture_id, uv, alpha: alpha.clamp(0.0, 1.0) });
}
pub fn inset_shadow(&mut self, rect: Rect, color: Color, radius: f32, blur_radius: f32) {
self.commands.push(PaintCommand::InsetShadow { rect, color, radius, blur_radius: blur_radius.max(0.0) });
}
pub fn backdrop_blur(&mut self, rect: Rect, radius: f32, blur_radius: f32, tint: Color) {
self.commands.push(PaintCommand::BackdropBlur {
rect,
radius: radius.max(0.0),
blur_radius: blur_radius.max(0.0),
tint,
});
}
pub fn push_blend_mode(&mut self, mode: BlendMode) {
self.commands.push(PaintCommand::PushBlendMode(mode));
}
pub fn pop_blend_mode(&mut self) {
self.commands.push(PaintCommand::PopBlendMode);
}
pub fn push_clip(&mut self, rect: Rect) {
self.commands.push(PaintCommand::PushClip(rect));
}
pub fn push_clip_rrect(&mut self, rect: Rect, radius: f32) {
self.commands.push(PaintCommand::PushClipRRect { rect, radius });
}
pub fn pop_clip(&mut self) {
self.commands.push(PaintCommand::PopClip);
}
pub fn is_empty(&self) -> bool {
self.commands.is_empty()
}
pub fn len(&self) -> usize {
self.commands.len()
}
}
#[derive(Clone, Copy, Debug)]
pub enum PathSeg {
Line(f32, f32),
Quad { cx: f32, cy: f32, x: f32, y: f32, flat: f32 },
Cubic { c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32, flat: f32 },
}
#[derive(Clone, Debug, Default)]
struct Contour {
start: (f32, f32),
segs: Vec<PathSeg>,
closed: bool,
}
impl PathSeg {
fn end(&self) -> (f32, f32) {
match *self {
PathSeg::Line(x, y) => (x, y),
PathSeg::Quad { x, y, .. } => (x, y),
PathSeg::Cubic { x, y, .. } => (x, y),
}
}
fn transform(&mut self, sx: f32, sy: f32, fscale: f32) {
match self {
PathSeg::Line(x, y) => {
*x *= sx;
*y *= sy;
}
PathSeg::Quad { cx, cy, x, y, flat } => {
*cx *= sx;
*cy *= sy;
*x *= sx;
*y *= sy;
*flat *= fscale;
}
PathSeg::Cubic { c1x, c1y, c2x, c2y, x, y, flat } => {
*c1x *= sx;
*c1y *= sy;
*c2x *= sx;
*c2y *= sy;
*x *= sx;
*y *= sy;
*flat *= fscale;
}
}
}
}
#[derive(Default, Clone, Debug)]
pub struct PathBuilder {
cx: f32,
cy: f32,
start: (f32, f32),
segs: Vec<PathSeg>,
contours: Vec<Contour>,
}
impl PathBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn transform(&mut self, sx: f32, sy: f32) {
let fscale = sx.abs().max(sy.abs());
for c in self.contours.iter_mut() {
c.start.0 *= sx;
c.start.1 *= sy;
for seg in c.segs.iter_mut() {
seg.transform(sx, sy, fscale);
}
}
self.start.0 *= sx;
self.start.1 *= sy;
for seg in self.segs.iter_mut() {
seg.transform(sx, sy, fscale);
}
self.cx *= sx;
self.cy *= sy;
}
fn flatten_contour(start: (f32, f32), segs: &[PathSeg], out: &mut Vec<(f32, f32)>) {
out.push(start);
let (mut x0, mut y0) = start;
for seg in segs {
match *seg {
PathSeg::Line(x, y) => out.push((x, y)),
PathSeg::Quad { cx, cy, x, y, flat } => flatten_quad_bezier(x0, y0, cx, cy, x, y, flat, out),
PathSeg::Cubic { c1x, c1y, c2x, c2y, x, y, flat } => {
flatten_cubic_bezier(x0, y0, c1x, c1y, c2x, c2y, x, y, flat, out)
}
}
x0 = seg.end().0;
y0 = seg.end().1;
}
}
pub fn move_to(&mut self, x: f32, y: f32) {
if !self.segs.is_empty() {
let segs = std::mem::take(&mut self.segs);
self.contours.push(Contour { start: self.start, segs, closed: false });
}
self.start = (x, y);
self.cx = x;
self.cy = y;
}
pub fn line_to(&mut self, x: f32, y: f32) {
self.segs.push(PathSeg::Line(x, y));
self.cx = x;
self.cy = y;
}
pub fn quad_to(&mut self, cx: f32, cy: f32, ex: f32, ey: f32, flat: f32) {
self.segs.push(PathSeg::Quad { cx, cy, x: ex, y: ey, flat });
self.cx = ex;
self.cy = ey;
}
#[allow(clippy::too_many_arguments)]
pub fn cubic_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, ex: f32, ey: f32, flat: f32) {
self.segs.push(PathSeg::Cubic { c1x, c1y, c2x, c2y, x: ex, y: ey, flat });
self.cx = ex;
self.cy = ey;
}
pub fn arc_to(&mut self, cx: f32, cy: f32, r: f32, start_angle: f32, end_angle: f32, num_segments: u32) {
if r <= 0.0 {
return;
}
let sweep = end_angle - start_angle;
let sweep = if sweep.abs() >= std::f32::consts::TAU { sweep * 0.999 } else { sweep };
let segs = (((sweep.abs() / std::f32::consts::FRAC_PI_2).ceil()) as u32).clamp(1, num_segments.max(1));
let step = sweep / segs as f32;
let flat = (r * step).abs() * 0.05;
let (sx, sy) = (cx + r * start_angle.cos(), cy + r * start_angle.sin());
let dcx = sx - self.cx;
let dcy = sy - self.cy;
if dcx * dcx + dcy * dcy > 1e-12 {
self.segs.push(PathSeg::Line(sx, sy));
self.cx = sx;
self.cy = sy;
}
let k = (4.0 / 3.0) * (step / 4.0).tan() * r; let mut a0 = start_angle;
for _ in 0..segs {
let a1 = a0 + step;
let (x0, y0) = (cx + r * a0.cos(), cy + r * a0.sin());
let (x1, y1) = (cx + r * a1.cos(), cy + r * a1.sin());
let c1x = x0 - k * a0.sin();
let c1y = y0 + k * a0.cos();
let c2x = x1 + k * a1.sin();
let c2y = y1 - k * a1.cos();
self.segs.push(PathSeg::Cubic { c1x, c1y, c2x, c2y, x: x1, y: y1, flat });
self.cx = x1;
self.cy = y1;
a0 = a1;
}
}
pub fn close(&mut self) {
if !self.segs.is_empty() {
let segs = std::mem::take(&mut self.segs);
self.contours.push(Contour { start: self.start, segs, closed: true });
}
}
pub fn paths(&self) -> Vec<Vec<(f32, f32)>> {
let mut out = Vec::with_capacity(self.contours.len());
for c in &self.contours {
let mut pts = Vec::new();
Self::flatten_contour(c.start, &c.segs, &mut pts);
if pts.first() == pts.last() && pts.len() > 1 {
pts.pop();
}
if pts.len() >= 2 {
out.push(pts);
}
}
if !self.segs.is_empty() {
let mut pts = Vec::new();
Self::flatten_contour(self.start, &self.segs, &mut pts);
if pts.first() == pts.last() && pts.len() > 1 {
pts.pop();
}
if pts.len() >= 2 {
out.push(pts);
}
}
out
}
pub fn curve_contours(&self) -> Vec<((f32, f32), Vec<PathSeg>, bool)> {
let mut out = Vec::with_capacity(self.contours.len() + 1);
for c in &self.contours {
out.push((c.start, c.segs.clone(), c.closed));
}
if !self.segs.is_empty() {
out.push((self.start, self.segs.clone(), false));
}
out
}
pub fn paths_with_closed(&self) -> Vec<(Vec<(f32, f32)>, bool)> {
let mut out = Vec::with_capacity(self.contours.len() + 1);
for c in &self.contours {
let mut pts = Vec::new();
Self::flatten_contour(c.start, &c.segs, &mut pts);
if pts.first() == pts.last() && pts.len() > 1 {
pts.pop();
}
if pts.len() >= 2 {
out.push((pts, c.closed));
}
}
if !self.segs.is_empty() {
let mut pts = Vec::new();
Self::flatten_contour(self.start, &self.segs, &mut pts);
if pts.first() == pts.last() && pts.len() > 1 {
pts.pop();
}
if pts.len() >= 2 {
out.push((pts, false));
}
}
out
}
pub fn fill(self, color: Color, list: &mut PaintList) {
if self.contours.is_empty() && self.segs.is_empty() {
return;
}
let mut clean_contours: Vec<Vec<(f32, f32)>> = Vec::with_capacity(self.contours.len());
for c in self.contours.iter() {
let mut pts = Vec::new();
Self::flatten_contour(c.start, &c.segs, &mut pts);
if pts.first() == pts.last() && pts.len() > 1 {
pts.pop();
}
if pts.len() >= 3 {
clean_contours.push(pts);
}
}
if clean_contours.is_empty() {
return;
}
let mut flat: Vec<(f32, f32)> = Vec::new();
let mut hole_offsets: Vec<usize> = Vec::new();
let mut first = true;
for contour in clean_contours.iter() {
if !first {
hole_offsets.push(flat.len());
}
first = false;
for &p in contour {
flat.push(p);
}
}
let (tri_points, indices) = earcut(&flat, if hole_offsets.is_empty() { None } else { Some(&hole_offsets) });
if indices.len() < 3 {
return;
}
let vertices: Vec<Vertex> = tri_points.iter().map(|&(x, y)| Vertex { x, y, color }).collect();
list.push(PaintCommand::Triangles { vertices, indices });
}
}
#[allow(dead_code)]
const MAX_FLATTEN_DEPTH: u32 = 10;
#[allow(clippy::too_many_arguments)]
fn flatten_quad_bezier(x0: f32, y0: f32, cx: f32, cy: f32, ex: f32, ey: f32, flat: f32, out: &mut Vec<(f32, f32)>) {
let dx = ex - x0;
let dy = ey - y0;
let len_sq = dx * dx + dy * dy;
if len_sq < 1e-6 {
out.push((ex, ey));
return;
}
let cross = dx * (cy - y0) - dy * (cx - x0);
let dist = (cross / len_sq.sqrt().max(1e-6)).abs();
if dist < flat {
out.push((ex, ey));
return;
}
let mx0 = (x0 + cx) / 2.0;
let my0 = (y0 + cy) / 2.0;
let mx1 = (cx + ex) / 2.0;
let my1 = (cy + ey) / 2.0;
let mx = (mx0 + mx1) / 2.0;
let my = (my0 + my1) / 2.0;
flatten_quad_bezier(x0, y0, mx0, my0, mx, my, flat, out);
flatten_quad_bezier(mx, my, mx1, my1, ex, ey, flat, out);
}
#[allow(dead_code, clippy::too_many_arguments)]
fn flatten_cubic_bezier(
x0: f32,
y0: f32,
x1: f32,
y1: f32,
x2: f32,
y2: f32,
x3: f32,
y3: f32,
flat: f32,
out: &mut Vec<(f32, f32)>,
) {
let dx = x3 - x0;
let dy = y3 - y0;
let len = (dx * dx + dy * dy).sqrt().max(1e-6);
let d1 = (dx * (y1 - y0) - dy * (x1 - x0)).abs() / len;
let d2 = (dx * (y2 - y0) - dy * (x2 - x0)).abs() / len;
if d1.max(d2) < flat {
out.push((x3, y3));
return;
}
let (mx01x, mx01y) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
let (mx12x, mx12y) = ((x1 + x2) / 2.0, (y1 + y2) / 2.0);
let (mx23x, mx23y) = ((x2 + x3) / 2.0, (y2 + y3) / 2.0);
let (mxx, mxy) = ((mx01x + mx12x) / 2.0, (mx01y + mx12y) / 2.0);
let (myy, myz) = ((mx12x + mx23x) / 2.0, (mx12y + mx23y) / 2.0);
let (midx, midy) = ((mxx + myy) / 2.0, (mxy + myz) / 2.0);
flatten_cubic_bezier(x0, y0, mx01x, mx01y, mxx, mxy, midx, midy, flat, out);
flatten_cubic_bezier(midx, midy, myy, myz, mx23x, mx23y, x3, y3, flat, out);
}
fn earcut(points: &[(f32, f32)], hole_offsets: Option<&[usize]>) -> (Vec<(f32, f32)>, Vec<u32>) {
let n = points.len();
if n < 3 {
return (Vec::new(), Vec::new());
}
if hole_offsets.is_none() {
return (points.to_vec(), earcut_single(points));
}
let hole_offsets = hole_offsets.unwrap();
let mut merged: Vec<(f32, f32)> = Vec::with_capacity(n + hole_offsets.len());
let first_end = hole_offsets.first().copied().unwrap_or(n);
merged.extend_from_slice(&points[0..first_end]);
let mut contour_start = first_end;
for &end_idx in hole_offsets.iter().skip(1) {
let hole = &points[contour_start..end_idx];
bridge_hole(&mut merged, hole);
contour_start = end_idx;
}
if contour_start < n {
let last = &points[contour_start..n];
bridge_hole(&mut merged, last);
}
let indices = earcut_single(&merged);
(merged, indices)
}
fn bridge_hole(outer: &mut Vec<(f32, f32)>, hole: &[(f32, f32)]) {
if hole.is_empty() {
return;
}
let mut hole = hole.to_vec();
let outer_ccw = area2(outer) > 0.0;
let hole_ccw = area2(&hole) > 0.0;
if hole_ccw == outer_ccw {
hole.reverse();
}
let hole_pt = hole[0];
let mut best_i = 0usize;
let mut best_d = f32::INFINITY;
for (i, &p) in outer.iter().enumerate() {
let d = (p.0 - hole_pt.0).powi(2) + (p.1 - hole_pt.1).powi(2);
if d < best_d {
best_d = d;
best_i = i;
}
}
let insert_pos = best_i + 1;
let skip_last = if hole.first() == hole.last() { hole.len() - 1 } else { hole.len() };
let bridge = outer[best_i];
outer.insert(insert_pos, bridge);
outer.splice(insert_pos + 1..insert_pos + 1, hole[..skip_last].iter().copied());
let close_pos = insert_pos + 1 + skip_last;
if let Some(&first) = hole.first() {
outer.insert(close_pos, first);
outer.insert(close_pos + 1, bridge);
}
}
fn earcut_single(points: &[(f32, f32)]) -> Vec<u32> {
let n = points.len();
let points = if points.first() == points.last() { &points[..n - 1] } else { points };
let n = points.len();
if n < 3 {
return Vec::new();
}
let mut result = Vec::with_capacity((n - 2) * 3);
let mut active: Vec<usize> = (0..n).collect();
let ccw = area2(points) > 0.0;
let mut safety = n * n; while active.len() >= 3 && safety > 0 {
safety -= 1;
if active.len() == 3 {
let (a, b, c) = (active[0], active[1], active[2]);
let (ax, ay) = points[a];
let (bx, by) = points[b];
let (cx, cy) = points[c];
let cross = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
if cross.abs() > 1e-6 {
result.push(a as u32);
result.push(b as u32);
result.push(c as u32);
}
break;
}
let m = active.len();
let mut found = None;
for j in 0..m {
let prev = active[(j + m - 1) % m];
let curr = active[j];
let next = active[(j + 1) % m];
if is_ear(points, prev, curr, next, ccw) {
found = Some(j);
break;
}
}
match found {
Some(j) => {
let prev = active[(j + m - 1) % m];
let curr = active[j];
let next = active[(j + 1) % m];
result.push(prev as u32);
result.push(curr as u32);
result.push(next as u32);
active.remove(j);
}
None => {
return fan_triangulation(points);
}
}
}
if result.is_empty() {
fan_triangulation(points)
} else {
result
}
}
fn area2(points: &[(f32, f32)]) -> f32 {
let mut a = 0.0f32;
for w in points.windows(2) {
a += w[0].0 * w[1].1 - w[1].0 * w[0].1;
}
if points.len() >= 2 {
a += points.last().unwrap().0 * points[0].1 - points[0].0 * points.last().unwrap().1;
}
a
}
fn is_ear(points: &[(f32, f32)], a: usize, b: usize, c: usize, ccw: bool) -> bool {
let (ax, ay) = points[a];
let (bx, by) = points[b];
let (cx, cy) = points[c];
let abc_cross = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
if (abc_cross > 0.0) != ccw {
return false;
}
for (i, &(px, py)) in points.iter().enumerate() {
if i == a || i == b || i == c {
continue;
}
if point_in_triangle(px, py, ax, ay, bx, by, cx, cy) {
return false;
}
}
true
}
#[allow(clippy::too_many_arguments)]
fn point_in_triangle(px: f32, py: f32, ax: f32, ay: f32, bx: f32, by: f32, cx: f32, cy: f32) -> bool {
let v0x = cx - ax;
let v0y = cy - ay;
let v1x = bx - ax;
let v1y = by - ay;
let v2x = px - ax;
let v2y = py - ay;
let dot00 = v0x * v0x + v0y * v0y;
let dot01 = v0x * v1x + v0y * v1y;
let dot02 = v0x * v2x + v0y * v2y;
let dot11 = v1x * v1x + v1y * v1y;
let dot12 = v1x * v2x + v1y * v2y;
let inv_denom = 1.0 / (dot00 * dot11 - dot01 * dot01).max(1e-9);
let u = (dot11 * dot02 - dot01 * dot12) * inv_denom;
let v = (dot00 * dot12 - dot01 * dot02) * inv_denom;
const EPS: f32 = 1e-6;
u > EPS && v > EPS && (u + v) < 1.0 - EPS
}
fn fan_triangulation(points: &[(f32, f32)]) -> Vec<u32> {
let mut result = Vec::new();
if points.len() < 3 {
return result;
}
let base = points[0];
for i in 2..points.len() {
let mut ok = true;
for j in 1..points.len() {
if j == i || j == 0 {
continue;
}
if point_in_triangle(
points[j].0,
points[j].1,
base.0,
base.1,
points[1].0,
points[1].1,
points[i].0,
points[i].1,
) {
ok = false;
break;
}
}
if ok {
result.push(0u32);
result.push(1u32);
result.push(i as u32);
}
}
if result.len() < 3 && points.len() >= 3 {
let n = points.len() as u32;
for i in 1..n - 1 {
result.push(0);
result.push(i);
result.push(i + 1);
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Color;
#[test]
fn path_builder_triangulates_square() {
let mut pb = PathBuilder::new();
pb.move_to(0.0, 0.0);
pb.line_to(100.0, 0.0);
pb.line_to(100.0, 100.0);
pb.line_to(0.0, 100.0);
pb.close();
let mut list = PaintList::new();
pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
assert_eq!(list.commands.len(), 1);
if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
assert_eq!(vertices.len(), 4);
assert_eq!(indices.len(), 6);
} else {
panic!("expected Triangles");
}
}
#[test]
fn path_builder_quadbezier_flattens() {
let mut pb = PathBuilder::new();
pb.move_to(0.0, 50.0);
pb.quad_to(50.0, 0.0, 100.0, 50.0, 0.5);
pb.quad_to(50.0, 100.0, 0.0, 50.0, 0.5);
pb.close();
let mut list = PaintList::new();
pb.fill(Color::rgb(0.0, 1.0, 0.0), &mut list);
assert_eq!(list.commands.len(), 1);
if let PaintCommand::Triangles { indices, .. } = &list.commands[0] {
assert!(indices.len() >= 6, "bezier triangulation should produce >= 6 indices, got {}", indices.len());
}
}
#[test]
fn path_builder_arc_to_produces_points() {
let mut pb = PathBuilder::new();
pb.move_to(100.0, 100.0);
pb.arc_to(100.0, 100.0, 50.0, 0.0, std::f32::consts::FRAC_PI_2, 16);
pb.close();
let mut list = PaintList::new();
pb.fill(Color::WHITE, &mut list);
if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
assert!(vertices.len() >= 4, "arc + close → 至少 4 vertices");
assert!(indices.len() >= 6, "earcut → 至少 1 triangle(3 indices)");
for v in vertices {
let dx = v.x - 100.0;
let dy = v.y - 100.0;
let d = (dx * dx + dy * dy).sqrt();
assert!((d - 50.0).abs() < 1.0 || d < 1.0, "vertex ({}, {}) should be at r≈50 or center", v.x, v.y);
}
}
}
#[test]
fn path_builder_annulus_sector_triangulates() {
let cx = 100.0;
let cy = 100.0;
let outer_r = 80.0;
let inner_r = 60.0;
let start_a = -std::f32::consts::FRAC_PI_2;
let end_a = start_a + std::f32::consts::TAU * 0.75; let segs = 32u32;
let mut pb = PathBuilder::new();
pb.move_to(cx + outer_r * start_a.cos(), cy + outer_r * start_a.sin());
pb.arc_to(cx, cy, outer_r, start_a, end_a, segs);
pb.line_to(cx + inner_r * end_a.cos(), cy + inner_r * end_a.sin());
pb.arc_to(cx, cy, inner_r, end_a, start_a, segs);
pb.close();
let mut list = PaintList::new();
pb.fill(Color::rgb(0.2, 0.6, 1.0), &mut list);
if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
assert!(vertices.len() >= 20, "annulus sector should have many vertices, got {}", vertices.len());
assert!(indices.len() >= 6, "should produce triangles");
for v in vertices {
let dx = v.x - cx;
let dy = v.y - cy;
let d = (dx * dx + dy * dy).sqrt();
let on_outer = (d - outer_r).abs() < 1.0;
let on_inner = (d - inner_r).abs() < 1.0;
let on_radial = v.y == cy; assert!(
on_outer || on_inner || on_radial,
"vertex ({}, {}) d={} not on inner/outer/radial",
v.x,
v.y,
d
);
}
}
}
#[test]
fn box_shadow_pads_four_sigma_and_shrinks_radius_on_negative_spread() {
let mut list = PaintList::new();
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);
match &list.commands[0] {
PaintCommand::BoxShadow { rect, radius, blur_radius, .. } => {
assert_eq!(*rect, Rect::new(-9.0, 2.0, 142.0, 92.0));
assert_eq!(*radius, 9.0, "正 spread 圆角增大");
assert_eq!(*blur_radius, 5.0);
}
other => panic!("expected BoxShadow, got {other:?}"),
}
let mut list = PaintList::new();
list.box_shadow(Rect::new(0.0, 0.0, 100.0, 50.0), Point::ZERO, 0.0, -4.0, Color::BLACK, 10.0);
match &list.commands[0] {
PaintCommand::BoxShadow { rect, radius, .. } => {
assert_eq!(*rect, Rect::new(4.0, 4.0, 92.0, 42.0));
assert_eq!(*radius, 6.0, "负 spread 圆角应收缩");
}
other => panic!("expected BoxShadow, got {other:?}"),
}
}
#[test]
fn path_builder_empty_nop() {
let pb = PathBuilder::new();
let mut list = PaintList::new();
pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
assert!(list.is_empty());
}
#[test]
fn earcut_simple_triangle() {
let pts = vec![(0.0, 0.0), (10.0, 0.0), (5.0, 10.0), (0.0, 0.0)];
let (points, indices) = earcut(&pts, None);
assert_eq!(indices.len(), 3);
let unique: std::collections::HashSet<&u32> = indices.iter().collect();
assert_eq!(unique.len(), 3); assert!(indices.iter().all(|&i| (i as usize) < points.len()));
}
fn tri_area_sum(points: &[(f32, f32)], indices: &[u32]) -> f32 {
let mut area = 0.0;
for t in indices.as_chunks::<3>().0 {
let (ax, ay) = points[t[0] as usize];
let (bx, by) = points[t[1] as usize];
let (cx, cy) = points[t[2] as usize];
area += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs() * 0.5;
}
area
}
#[test]
fn earcut_concave_polygon_area_matches() {
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)];
let (points, indices) = earcut(&pts, None);
assert_eq!(indices.len(), 12, "6 顶点凹多边形 → 4 个三角形");
assert!(indices.iter().all(|&i| (i as usize) < points.len()));
let expected = area2(&pts).abs() * 0.5;
let got = tri_area_sum(&points, &indices);
assert!((got - expected).abs() < 0.5, "凹多边形面积: expected={expected}, got={got}");
}
#[test]
fn earcut_donut_hole_area_subtracted() {
let outer = vec![(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
let hole = vec![(25.0, 25.0), (75.0, 25.0), (75.0, 75.0), (25.0, 75.0)];
let mut pts = outer.clone();
pts.extend_from_slice(&hole);
let (points, indices) = earcut(&pts, Some(&[outer.len()]));
assert!(!indices.is_empty());
assert!(indices.iter().all(|&i| (i as usize) < points.len()), "索引不得越界");
let got = tri_area_sum(&points, &indices);
let expected = 100.0 * 100.0 - 50.0 * 50.0;
assert!((got - expected).abs() < 1.0, "带洞面积: expected={expected}, got={got}");
}
#[test]
fn fill_multi_contour_indices_in_range() {
let mut pb = PathBuilder::new();
pb.move_to(0.0, 0.0);
pb.line_to(100.0, 0.0);
pb.line_to(100.0, 100.0);
pb.line_to(0.0, 100.0);
pb.close();
pb.move_to(40.0, 40.0);
pb.line_to(60.0, 40.0);
pb.line_to(50.0, 60.0);
pb.close();
let mut list = PaintList::new();
pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
assert_eq!(list.commands.len(), 1);
if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
assert!(
indices.iter().all(|&i| (i as usize) < vertices.len()),
"索引 {} 越界(vertices.len={})",
indices.iter().max().unwrap(),
vertices.len()
);
} else {
panic!("expected Triangles");
}
}
}