use std::fmt::Display;
use std::sync::Arc;
use valo::DisplayList;
use valo::DisplayListBuilder;
use valo::Op;
use crate::{Matrix4, Offset, Rect};
pub type Canvas = DisplayListBuilder;
pub type Picture = DisplayList;
pub type StrokeCap = valo::Cap;
pub type PathFillType = valo::FillRule;
pub type PaintingStyle = valo::PaintStyle;
pub fn flattened_ops(picture: &Picture) -> Vec<Op> {
let mut ops = Vec::new();
flatten_into(picture, &mut ops);
ops
}
fn flatten_into(picture: &Picture, ops: &mut Vec<Op>) {
for op in picture.ops() {
ops.push(op.clone());
if let Op::DrawDisplayList { list, .. } = op {
flatten_into(list, ops);
}
}
}
pub use valo::{
Backdrop, BlendMode, BlurStyle, ClipOp, FillRule, Image, MaskBlur, Paint, PaintStyle,
PathBuilder, PathOperation, Shader, Stroke,
};
#[derive(Clone, Debug, PartialEq)]
pub struct Path {
contours: Arc<valo::Path>,
pub fill_type: PathFillType,
}
impl Path {
pub fn new(contours: Arc<valo::Path>) -> Path {
Path {
contours,
fill_type: PathFillType::NonZero,
}
}
pub fn as_valo(&self) -> &Arc<valo::Path> {
&self.contours
}
pub fn contains(&self, point: Offset) -> bool {
self.contours.contains(point.into(), self.fill_type)
}
pub fn get_bounds(&self) -> Rect {
let bounds = self.contours.bounds();
Rect::from_ltwh(
f64::from(bounds.x),
f64::from(bounds.y),
f64::from(bounds.width),
f64::from(bounds.height),
)
}
pub fn shift(&self, offset: Offset) -> Path {
if offset == Offset::ZERO {
return self.clone();
}
self.transform(&Matrix4::translation(
offset.dx() as f32,
offset.dy() as f32,
))
}
pub fn transform(&self, matrix: &Matrix4) -> Path {
Path {
contours: self.contours.transformed(matrix),
fill_type: self.fill_type,
}
}
}
impl From<Arc<valo::Path>> for Path {
fn from(contours: Arc<valo::Path>) -> Path {
Path::new(contours)
}
}
pub fn path_combine(operation: PathOperation, path1: &Path, path2: &Path) -> Path {
let contours = path1
.contours
.combine(path1.fill_type, operation, &path2.contours, path2.fill_type)
.unwrap_or_else(|_| {
panic!(
"Path.combine() failed. This may be due an invalid path; in particular, check for NaN values."
)
});
Path {
contours,
fill_type: PathFillType::EvenOdd,
}
}
pub use valo;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FilterQuality {
None,
Low,
Medium,
High,
}
impl FilterQuality {
pub fn to_valo(self) -> valo::Sampling {
let (filter, mipmap) = match self {
FilterQuality::None => (valo::Filter::Nearest, valo::MipmapMode::None),
FilterQuality::Low => (valo::Filter::Linear, valo::MipmapMode::None),
FilterQuality::Medium | FilterQuality::High => {
(valo::Filter::Linear, valo::MipmapMode::Linear)
}
};
valo::Sampling {
filter,
mipmap,
tile_x: valo::TileMode::Clamp,
tile_y: valo::TileMode::Clamp,
}
}
}
impl std::fmt::Display for FilterQuality {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let name = match self {
FilterQuality::None => "none",
FilterQuality::Low => "low",
FilterQuality::Medium => "medium",
FilterQuality::High => "high",
};
write!(f, "FilterQuality.{name}")
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ColorFilter {
Mode {
color: crate::Color,
blend_mode: BlendMode,
},
Matrix([f64; 20]),
LinearToSrgbGamma,
SrgbToLinearGamma,
}
impl ColorFilter {
pub const fn mode(color: crate::Color, blend_mode: BlendMode) -> ColorFilter {
ColorFilter::Mode { color, blend_mode }
}
pub const fn matrix(matrix: [f64; 20]) -> ColorFilter {
ColorFilter::Matrix(matrix)
}
pub const fn linear_to_srgb_gamma() -> ColorFilter {
ColorFilter::LinearToSrgbGamma
}
pub const fn srgb_to_linear_gamma() -> ColorFilter {
ColorFilter::SrgbToLinearGamma
}
pub fn saturation(saturation: f64) -> ColorFilter {
const R_LUMINANCE: f64 = 0.2126;
const G_LUMINANCE: f64 = 0.7152;
const B_LUMINANCE: f64 = 0.0722;
let inv_sat = 1.0 - saturation;
ColorFilter::matrix([
inv_sat * R_LUMINANCE + saturation,
inv_sat * G_LUMINANCE,
inv_sat * B_LUMINANCE,
0.0,
0.0,
inv_sat * R_LUMINANCE,
inv_sat * G_LUMINANCE + saturation,
inv_sat * B_LUMINANCE,
0.0,
0.0,
inv_sat * R_LUMINANCE,
inv_sat * G_LUMINANCE,
inv_sat * B_LUMINANCE + saturation,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
])
}
pub fn debug_short_description(&self) -> String {
match self {
ColorFilter::Mode { color, blend_mode } => {
format!("ColorFilter.mode({color:?}, {blend_mode:?})")
}
ColorFilter::Matrix(matrix) => format!("ColorFilter.matrix({matrix:?})"),
ColorFilter::LinearToSrgbGamma => String::from("ColorFilter.linearToSrgbGamma()"),
ColorFilter::SrgbToLinearGamma => String::from("ColorFilter.srgbToLinearGamma()"),
}
}
}
impl std::fmt::Display for ColorFilter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.debug_short_description())
}
}
impl ColorFilter {
pub fn to_valo(&self) -> valo::ColorFilter {
match *self {
ColorFilter::Mode { color, blend_mode } => {
valo::ColorFilter::Blend(color.into(), blend_mode)
}
ColorFilter::Matrix(matrix) => valo::ColorFilter::Matrix(valo_matrix(matrix)),
ColorFilter::LinearToSrgbGamma => valo::ColorFilter::LinearToSrgbGamma,
ColorFilter::SrgbToLinearGamma => valo::ColorFilter::SrgbToLinearGamma,
}
}
}
fn valo_matrix(matrix: [f64; 20]) -> [f32; 20] {
const ROW_LENGTH: usize = 5;
const TRANSLATION_COLUMN: usize = 4;
std::array::from_fn(|index| {
let entry = matrix[index];
let entry = if index % ROW_LENGTH == TRANSLATION_COLUMN {
entry / 255.0
} else {
entry
};
entry as f32
})
}
#[derive(Clone, Debug, PartialEq)]
pub enum ImageFilter {
Blur {
sigma_x: f64,
sigma_y: f64,
bounds: Option<crate::Rect>,
},
Color(ColorFilter),
Compose {
outer: Arc<ImageFilter>,
inner: Arc<ImageFilter>,
},
Matrix {
data: crate::Matrix4,
filter_quality: FilterQuality,
},
Shader {
shader: valo::RuntimeShader,
filter_quality: FilterQuality,
},
}
impl ImageFilter {
pub const fn blur(sigma_x: f64, sigma_y: f64) -> ImageFilter {
ImageFilter::Blur {
sigma_x,
sigma_y,
bounds: None,
}
}
pub fn bounds(self, bounds: crate::Rect) -> ImageFilter {
match self {
ImageFilter::Blur {
sigma_x, sigma_y, ..
} => ImageFilter::Blur {
sigma_x,
sigma_y,
bounds: Some(bounds),
},
other => other,
}
}
pub const fn matrix(matrix4: crate::Matrix4, filter_quality: FilterQuality) -> ImageFilter {
ImageFilter::Matrix {
data: matrix4,
filter_quality,
}
}
#[cfg_attr(
target_arch = "wasm32",
expect(
clippy::arc_with_non_send_sync,
reason = "a shader filter's images are the web's GPU objects, which stay on their \
thread there; a filter crosses threads with its picture elsewhere"
)
)]
pub fn compose(outer: ImageFilter, inner: ImageFilter) -> ImageFilter {
ImageFilter::Compose {
outer: Arc::new(outer),
inner: Arc::new(inner),
}
}
pub fn shader(shader: &crate::FragmentShader, filter_quality: FilterQuality) -> ImageFilter {
let invalid_floats = shader.float_count() < 2;
let invalid_sampler = !shader.validate_image_filter();
if invalid_floats || invalid_sampler {
let mut buffer = String::from(
"ImageFilter.shader requires that the first uniform is a vec2 and at least one \
sampler uniform is present.\n",
);
if invalid_floats {
buffer.push_str("The shader has fewer than two float uniforms.\n");
}
if invalid_sampler {
buffer.push_str("The shader is missing a sampler uniform.\n");
}
panic!("{buffer}");
}
let shader = shader.as_image_filter(filter_quality.to_valo());
if let Err(error) = valo::ImageFilter::runtime(shader.clone()) {
panic!("ImageFilter.shader requires that the first uniform is a vec2: {error}");
}
ImageFilter::Shader {
shader,
filter_quality,
}
}
pub const fn is_shader_filter_supported() -> bool {
true
}
pub fn debug_short_description(&self) -> String {
match self {
ImageFilter::Blur {
sigma_x,
sigma_y,
bounds,
} => {
let bounds = match bounds {
Some(bounds) => format!(", bounds: {bounds:?}"),
None => String::new(),
};
format!("blur({sigma_x}, {sigma_y}, unspecified{bounds})")
}
ImageFilter::Color(filter) => filter.debug_short_description(),
ImageFilter::Matrix {
data,
filter_quality,
} => format!("matrix({:?}, {filter_quality})", data.to_flutter_array()),
ImageFilter::Compose { outer, inner } => format!(
"{} -> {}",
inner.debug_short_description(),
outer.debug_short_description()
),
ImageFilter::Shader { .. } => String::from("shader"),
}
}
}
impl std::fmt::Display for ImageFilter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ImageFilter::Blur { .. } | ImageFilter::Matrix { .. } => {
write!(f, "ImageFilter.{}", self.debug_short_description())
}
ImageFilter::Color(filter) => Display::fmt(filter, f),
ImageFilter::Compose { .. } => write!(
f,
"ImageFilter.compose(source -> {} -> result)",
self.debug_short_description()
),
ImageFilter::Shader {
shader,
filter_quality,
} => write!(
f,
"ImageFilter.shader(Shader#{}, {filter_quality})",
shader.effect.id()
),
}
}
}
impl ImageFilter {
pub fn to_valo(&self) -> valo::ImageFilter {
match self {
ImageFilter::Blur {
sigma_x,
sigma_y,
bounds,
} => {
let (sigma_x, sigma_y) = (*sigma_x as f32, *sigma_y as f32);
match bounds {
Some(bounds) => {
valo::ImageFilter::bounded_blur(sigma_x, sigma_y, (*bounds).into())
}
None => valo::ImageFilter::blur(sigma_x, sigma_y),
}
}
ImageFilter::Color(filter) => valo::ImageFilter::Color(filter.to_valo()),
ImageFilter::Matrix {
data,
filter_quality,
} => valo::ImageFilter::matrix(*data, filter_quality.to_valo()),
ImageFilter::Compose { outer, inner } => {
valo::ImageFilter::compose(outer.to_valo(), inner.to_valo())
}
ImageFilter::Shader { shader, .. } => valo::ImageFilter::Runtime(shader.clone()),
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::{
ColorFilter, FilterQuality, ImageFilter, Path, PathBuilder, PathFillType, PathOperation,
path_combine, valo,
};
use crate::{BlendMode, Color, Matrix4, Offset, Rect};
#[test]
fn a_saturation_of_one_is_the_identity_matrix() {
let ColorFilter::Matrix(matrix) = ColorFilter::saturation(1.0) else {
panic!("saturation is a matrix filter");
};
let identity = [
1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, ];
for (value, expected) in matrix.iter().zip(identity) {
assert!((value - expected).abs() < 1e-12, "{matrix:?}");
}
}
#[test]
fn a_matrix_filter_reaches_valo_with_its_sampling_and_prints_as_darts() {
let scale = Matrix4::scale(2.0, 2.0);
let filter = ImageFilter::matrix(scale, FilterQuality::Low);
assert_eq!(
filter.to_valo(),
valo::ImageFilter::matrix(scale, FilterQuality::Low.to_valo())
);
assert_eq!(
filter.to_string(),
"ImageFilter.matrix([2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, \
0.0, 0.0, 0.0, 1.0], FilterQuality.low)"
);
}
#[test]
fn combining_two_paths_cuts_one_from_the_other() {
let mut host = PathBuilder::new();
host.rect(Rect::from_ltwh(0.0, 0.0, 100.0, 100.0).into());
let mut guest = PathBuilder::new();
guest.rect(Rect::from_ltwh(50.0, -10.0, 100.0, 60.0).into());
let notched = path_combine(
PathOperation::Difference,
&Path::new(host.build()),
&Path::new(guest.build()),
);
assert_eq!(notched.fill_type, PathFillType::EvenOdd);
let contains = |x: f64, y: f64| notched.contains(Offset::new(x, y));
assert!(contains(25.0, 25.0));
assert!(!contains(75.0, 25.0), "the guest is cut out");
assert!(contains(75.0, 75.0));
assert!(!contains(125.0, 25.0), "nothing of the guest is added");
}
#[test]
fn a_combined_path_leaves_the_hole_of_a_guest_wholly_inside() {
let mut host = PathBuilder::new();
host.rect(Rect::from_ltwh(0.0, 0.0, 100.0, 100.0).into());
let mut guest = PathBuilder::new();
guest.rect(Rect::from_ltwh(25.0, 25.0, 50.0, 50.0).into());
let holed = path_combine(
PathOperation::Difference,
&Path::new(host.build()),
&Path::new(guest.build()),
);
assert!(holed.contains(Offset::new(10.0, 10.0)));
assert!(
!holed.contains(Offset::new(50.0, 50.0)),
"the guest is a hole"
);
}
#[test]
fn combining_reads_each_path_with_its_own_fill_type() {
let mut ring = PathBuilder::new();
ring.rect(Rect::from_ltwh(0.0, 0.0, 100.0, 100.0).into());
ring.rect(Rect::from_ltwh(25.0, 25.0, 50.0, 50.0).into());
let mut even_odd = Path::new(ring.build());
even_odd.fill_type = PathFillType::EvenOdd;
let non_zero = Path::new(Arc::clone(even_odd.as_valo()));
let mut point = PathBuilder::new();
point.rect(Rect::from_ltwh(40.0, 40.0, 20.0, 20.0).into());
let point = Path::new(point.build());
let through_the_hole = path_combine(PathOperation::Intersect, &even_odd, &point);
assert!(!through_the_hole.contains(Offset::new(50.0, 50.0)));
let over_the_fill = path_combine(PathOperation::Intersect, &non_zero, &point);
assert!(over_the_fill.contains(Offset::new(50.0, 50.0)));
}
#[test]
fn a_path_keeps_its_fill_type_through_a_shift_and_a_transform() {
let mut builder = PathBuilder::new();
builder.rect(Rect::from_ltwh(0.0, 0.0, 10.0, 10.0).into());
let mut path = Path::new(builder.build());
assert_eq!(path.fill_type, PathFillType::NonZero);
path.fill_type = PathFillType::EvenOdd;
let shifted = path.shift(Offset::new(5.0, 0.0));
assert_eq!(shifted.fill_type, PathFillType::EvenOdd);
assert!(shifted.contains(Offset::new(12.0, 5.0)));
assert!(!shifted.contains(Offset::new(2.0, 5.0)));
let scaled = path.transform(&Matrix4::scale(2.0, 2.0));
assert_eq!(scaled.fill_type, PathFillType::EvenOdd);
assert!(scaled.contains(Offset::new(15.0, 15.0)));
}
#[test]
fn a_blur_reports_its_bounds_and_a_composition_reads_inner_then_outer() {
let blur = ImageFilter::blur(2.0, 3.0).bounds(Rect::from_ltwh(0.0, 0.0, 4.0, 5.0));
assert_eq!(
blur.debug_short_description(),
"blur(2, 3, unspecified, bounds: Rect.fromLTRB(0.0, 0.0, 4.0, 5.0))"
);
let tint = ImageFilter::Color(ColorFilter::mode(
Color::new(0xFF000000),
BlendMode::SrcOver,
));
let composed = ImageFilter::compose(tint, ImageFilter::blur(2.0, 3.0));
assert_eq!(
composed.to_string(),
"ImageFilter.compose(source -> blur(2, 3, unspecified) -> \
ColorFilter.mode(Color(alpha: 1.0000, red: 0.0000, green: 0.0000, blue: 0.0000, \
colorSpace: ColorSpace.sRGB), SrcOver) -> result)"
);
}
#[test]
fn a_colour_matrix_reaches_valo_with_its_translation_in_the_channels_range() {
let mut matrix = [0.0; 20];
matrix[0] = 2.0;
matrix[4] = 51.0;
matrix[18] = 1.0;
matrix[19] = 255.0;
let valo::ColorFilter::Matrix(replayed) = ColorFilter::matrix(matrix).to_valo() else {
panic!("a matrix reaches valo as a matrix");
};
assert_eq!(
[replayed[0], replayed[4], replayed[18], replayed[19]],
[2.0, 0.2, 1.0, 1.0]
);
}
#[test]
fn a_mode_filter_reaches_valo_as_a_blend_and_a_gamma_curve_as_the_same_curve() {
let green = Color::new(0x8C00FF00);
assert_eq!(
ColorFilter::mode(green, BlendMode::Darken).to_valo(),
valo::ColorFilter::Blend(green.into(), BlendMode::Darken)
);
assert_eq!(
ColorFilter::linear_to_srgb_gamma().to_valo(),
valo::ColorFilter::LinearToSrgbGamma
);
assert_eq!(
ColorFilter::srgb_to_linear_gamma().to_valo(),
valo::ColorFilter::SrgbToLinearGamma
);
}
#[test]
fn a_composition_reaches_valo_in_its_order_with_both_sigmas_and_the_bounds() {
let tint = ColorFilter::mode(Color::new(0xFF0000FF), BlendMode::Multiply);
let bounds = Rect::from_ltwh(0.0, 0.0, 4.0, 4.0);
let filter = ImageFilter::compose(
ImageFilter::Color(tint),
ImageFilter::blur(2.0, 5.0).bounds(bounds),
);
assert_eq!(
filter.to_valo(),
valo::ImageFilter::compose(
valo::ImageFilter::Color(valo::ColorFilter::Blend(
Color::new(0xFF0000FF).into(),
BlendMode::Multiply
)),
valo::ImageFilter::bounded_blur(2.0, 5.0, bounds.into()),
)
);
}
#[test]
fn a_gamma_curve_reaches_valo_in_its_place_in_a_composition() {
let filter = ImageFilter::compose(
ImageFilter::Color(ColorFilter::linear_to_srgb_gamma()),
ImageFilter::blur(3.0, 3.0),
);
assert_eq!(
filter.to_valo(),
valo::ImageFilter::compose(
valo::ImageFilter::Color(valo::ColorFilter::LinearToSrgbGamma),
valo::ImageFilter::blur(3.0, 3.0),
)
);
}
}