1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
use std::cell::RefCell;

use crate::colorspace::Color;

#[derive(Default, Copy, Clone, Debug)]
pub struct RadialGradient {
    pub x0: f64,
    pub y0: f64,
    pub r0: f64,
    pub x1: f64,
    pub y1: f64,
    pub r1: f64,
}

impl RadialGradient {
    // may be use Point`s
    pub fn new(x0: f64, y0: f64, r0: f64, x1: f64, y1: f64, r1: f64) -> Self {
        Self {
            x0,
            y0,
            r0,
            x1,
            y1,
            r1,
        }
    }
}

#[derive(Default, Copy, Clone, Debug)]
pub struct LinearGradient {
    pub x0: f64,
    pub y0: f64,
    pub x1: f64,
    pub y1: f64,
}

impl LinearGradient {
    // may be use Point`s
    pub fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Self {
        Self { x0, y0, x1, y1 }
    }
}

#[derive(Copy, Clone, Debug)]
pub struct ColorStop {
    pub offset: f64,
    pub color: Color,
}

impl ColorStop {
    pub fn new(offset: f64, color: Color) -> Self {
        Self { offset, color }
    }
}

/// A representation of the RGB (Red, Green, Blue) color space.
#[derive(Copy, Clone, Debug)]
pub enum GradientType {
    Linear(LinearGradient),
    Radial(RadialGradient),
}

impl Default for GradientType {
    fn default() -> Self {
        GradientType::Linear(Default::default())
    }
}

#[derive(Clone, Debug)]
pub struct Gradient {
    pub kind: GradientType,
    pub stops: RefCell<Vec<ColorStop>>,
}

impl Gradient {
    pub fn new(kind: GradientType) -> Self {
        Self {
            kind,
            stops: Default::default(),
        }
    }

    pub fn add_color_stop(&self, stop: ColorStop) {
        let mut stops = self.stops.borrow_mut();
        stops.push(stop)
    }

    pub fn get_color_count(&self) -> usize {
        let stops = self.stops.borrow();
        stops.len()
    }

    pub fn get_color_stop(&self, index: usize) -> Option<ColorStop> {
        let stops = self.stops.borrow();
        stops.get(index).copied()
    }
}

impl Default for Gradient {
    fn default() -> Self {
        Self {
            kind: Default::default(),
            stops: Default::default(),
        }
    }
}