use std::{
hash::{DefaultHasher, Hash, Hasher},
sync::{Arc, OnceLock},
};
use tiny_skia::{
FilterQuality, GradientStop, LinearGradient, Pattern, Pixmap, Point, RadialGradient, Shader, SpreadMode,
};
use super::{CanvasColor, transform};
use crate::node::{color::Color, transform::Transform2D};
pub const MAX_GRADIENT_STOPS: usize = 16;
pub const MIN_GRADIENT_STOPS: usize = 2;
pub const RAMP_TEXELS: usize = 256;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum GradientKind {
#[default]
Linear,
Radial,
Angular,
}
#[derive(Debug)]
pub(crate) struct Ramp {
pub id: u64,
pub texels: Arc<Vec<u8>>,
}
#[derive(Clone, Debug)]
pub struct Gradient {
kind: GradientKind,
center: [f32; 2],
size: [f32; 2],
rotation: f32,
stops: Vec<(f32, Color)>,
ramp: Arc<OnceLock<Ramp>>,
}
impl PartialEq for Gradient {
fn eq(&self, other: &Self) -> bool {
self.kind == other.kind
&& self.center == other.center
&& self.size == other.size
&& self.rotation == other.rotation
&& self.stops == other.stops
}
}
impl Gradient {
pub fn new(kind: GradientKind) -> Self {
Self {
kind,
center: [0.5, 0.5],
size: [1.0, 1.0],
rotation: 0.0,
stops: Vec::new(),
ramp: Arc::new(OnceLock::new()),
}
}
pub fn linear() -> Self {
Self::new(GradientKind::Linear)
}
pub fn radial() -> Self {
Self::new(GradientKind::Radial)
}
pub fn angular() -> Self {
Self::new(GradientKind::Angular)
}
fn edited(mut self) -> Self {
self.ramp = Arc::new(OnceLock::new());
self
}
pub fn center(mut self, x: f32, y: f32) -> Self {
self.center = [x, y];
self.edited()
}
pub fn size(mut self, width: f32, height: f32) -> Self {
self.size = [width, height];
self.edited()
}
pub fn rotation(mut self, radians: f32) -> Self {
self.rotation = radians;
self.edited()
}
pub fn stop(mut self, offset: f32, color: impl CanvasColor) -> Self {
if let Some(color) = color.canvas_color()
&& self.stops.len() < MAX_GRADIENT_STOPS
{
self.stops.push((offset, color));
}
self.edited()
}
pub fn kind(&self) -> GradientKind {
self.kind
}
pub fn stops(&self) -> &[(f32, Color)] {
&self.stops
}
pub fn is_valid(&self) -> bool {
if !(MIN_GRADIENT_STOPS..=MAX_GRADIENT_STOPS).contains(&self.stops.len()) {
return false;
}
let mut previous = f32::NEG_INFINITY;
for (offset, _) in &self.stops {
if !offset.is_finite() || !(0.0..=1.0).contains(offset) || *offset < previous {
return false;
}
previous = *offset;
}
self
.center
.iter()
.chain(self.size.iter())
.chain(std::iter::once(&self.rotation))
.all(|v| v.is_finite())
&& self.size[0] != 0.0
&& self.size[1] != 0.0
}
pub(crate) fn ramp(&self) -> &Ramp {
self.ramp.get_or_init(|| {
let mut texels = vec![0u8; RAMP_TEXELS * 4];
for (index, texel) in texels.chunks_exact_mut(4).enumerate() {
let t = (index as f32 + 0.5) / RAMP_TEXELS as f32;
texel.copy_from_slice(&self.sample(t));
}
let mut hash = DefaultHasher::new();
texels.hash(&mut hash);
Ramp {
id: (hash.finish() & ((1 << 62) - 1)) | (1 << 62),
texels: Arc::new(texels),
}
})
}
fn sample(&self, t: f32) -> [u8; 4] {
let channels = |c: &Color| [c.r(), c.g(), c.b(), c.a()].map(|v| f32::from(v) / 255.0);
let first = &self.stops[0];
let last = &self.stops[self.stops.len() - 1];
let straight = if t <= first.0 {
channels(&first.1)
} else if t >= last.0 {
channels(&last.1)
} else {
let index = self
.stops
.windows(2)
.position(|w| t >= w[0].0 && t <= w[1].0)
.unwrap_or(0);
let (a, b) = (&self.stops[index], &self.stops[index + 1]);
let span = b.0 - a.0;
let k = if span > 0.0 { (t - a.0) / span } else { 0.0 };
let (ca, cb) = (channels(&a.1), channels(&b.1));
[0, 1, 2, 3].map(|i| ca[i] + (cb[i] - ca[i]) * k)
};
let alpha = straight[3].clamp(0.0, 1.0);
[straight[0] * alpha, straight[1] * alpha, straight[2] * alpha, alpha]
.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
}
pub(crate) fn parameter(kind: GradientKind, x: f32, y: f32) -> f32 {
match kind {
GradientKind::Linear => x * 0.5 + 0.5,
GradientKind::Radial => x.hypot(y),
GradientKind::Angular => {
let turn = y.atan2(x) / std::f32::consts::TAU;
turn - turn.floor()
}
}
}
pub(crate) fn frame_from_box(&self, bounds: [f32; 4]) -> Option<Transform2D> {
let [x, y, width, height] = bounds;
if !bounds.iter().all(|v| v.is_finite()) || width == 0.0 || height == 0.0 {
return None;
}
let (cx, cy) = (x + self.center[0] * width, y + self.center[1] * height);
let (sx, sy) = (self.size[0], self.size[1]);
if sx == 0.0 || sy == 0.0 {
return None;
}
let frame = Transform2D::scale(1.0 / sx, 1.0 / sy)
.then(&Transform2D::rotate(-self.rotation))
.then(&Transform2D::scale(2.0 / width, 2.0 / height))
.then(&Transform2D::translate(-cx, -cy));
[frame.a, frame.b, frame.c, frame.d, frame.tx, frame.ty]
.iter()
.all(|v| v.is_finite())
.then_some(frame)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Paint {
Solid(Color),
Gradient {
gradient: Gradient,
bounds: [f32; 4],
},
}
impl Paint {
pub fn color(&self) -> Option<Color> {
match self {
Self::Solid(color) => Some(*color),
Self::Gradient { .. } => None,
}
}
pub(crate) fn gradient(&self) -> Option<(&Gradient, [f32; 4])> {
match self {
Self::Solid(_) => None,
Self::Gradient { gradient, bounds } => Some((gradient, *bounds)),
}
}
}
impl Gradient {
pub fn in_box(self, x: f32, y: f32, width: f32, height: f32) -> Paint {
Paint::Gradient {
gradient: self,
bounds: [x, y, width, height],
}
}
}
impl From<Color> for Paint {
fn from(color: Color) -> Self {
Self::Solid(color)
}
}
pub trait CanvasPaint {
fn canvas_paint(&self) -> Option<Paint>;
}
impl CanvasPaint for Paint {
fn canvas_paint(&self) -> Option<Paint> {
Some(self.clone())
}
}
impl CanvasPaint for Color {
fn canvas_paint(&self) -> Option<Paint> {
Some(Paint::Solid(*self))
}
}
impl CanvasPaint for &str {
fn canvas_paint(&self) -> Option<Paint> {
self.canvas_color().map(Paint::Solid)
}
}
impl CanvasPaint for String {
fn canvas_paint(&self) -> Option<Paint> {
self.canvas_color().map(Paint::Solid)
}
}
pub(crate) fn skia_shader<'a>(
gradient: &Gradient,
frame_to_target: Transform2D,
conic: Option<(&'a Pixmap, (i32, i32))>,
) -> Option<Shader<'a>> {
if !gradient.is_valid() {
return None;
}
if gradient.kind == GradientKind::Angular {
let (pixmap, origin) = conic?;
return Some(Pattern::new(
pixmap.as_ref(),
SpreadMode::Pad,
FilterQuality::Nearest,
1.0,
tiny_skia::Transform::from_translate(origin.0 as f32, origin.1 as f32),
));
}
let stops: Vec<GradientStop> = gradient
.stops
.iter()
.map(|(offset, color)| {
GradientStop::new(
*offset,
tiny_skia::Color::from_rgba8(color.r(), color.g(), color.b(), color.a()),
)
})
.collect();
let matrix = transform(frame_to_target);
match gradient.kind {
GradientKind::Linear => LinearGradient::new(
Point::from_xy(-1.0, 0.0),
Point::from_xy(1.0, 0.0),
stops,
SpreadMode::Pad,
matrix,
),
_ => RadialGradient::new(
Point::from_xy(0.0, 0.0),
Point::from_xy(0.0, 0.0),
1.0,
stops,
SpreadMode::Pad,
matrix,
),
}
}
pub(crate) fn angular_pixmap(
gradient: &Gradient,
frame_from_target: Transform2D,
origin: (i32, i32),
width: u32,
height: u32,
) -> Option<Pixmap> {
if !gradient.is_valid() || width == 0 || height == 0 {
return None;
}
let mut pixmap = Pixmap::new(width, height)?;
let ramp = gradient.ramp();
let texels = ramp.texels.as_ref();
let data = pixmap.data_mut();
for y in 0..height {
for x in 0..width {
let (u, v) =
frame_from_target.transform_point(x as f32 + origin.0 as f32 + 0.5, y as f32 + origin.1 as f32 + 0.5);
let t = Gradient::parameter(GradientKind::Angular, u, v);
let index = ((t * RAMP_TEXELS as f32) as usize).min(RAMP_TEXELS - 1) * 4;
let out = ((y * width + x) * 4) as usize;
data[out..out + 4].copy_from_slice(&texels[index..index + 4]);
}
}
Some(pixmap)
}