-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
gradient.rs
52 lines (44 loc) · 1.42 KB
/
gradient.rs
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
use crate::color::Color;
use core::cmp;
use core::fmt::{self, Debug};
#[cfg(feature = "std")]
use std::panic::{RefUnwindSafe, UnwindSafe};
#[cfg(feature = "std")]
type DynEvalGradient = dyn EvalGradient + Send + Sync + UnwindSafe + RefUnwindSafe;
#[cfg(not(feature = "std"))]
type DynEvalGradient = dyn EvalGradient + Send + Sync;
#[derive(Copy, Clone)]
pub struct Gradient {
pub(crate) eval: &'static DynEvalGradient,
}
impl Gradient {
/// Samples the gradient at position `i/n`. Requires `0 ≤ i < n`.
pub fn eval_rational(&self, i: usize, n: usize) -> Color {
if n == 0 {
panic!("invalid argument n=0 in Gradient::eval_rational");
}
let i = cmp::min(i, n - 1);
self.eval.eval_rational(i, n)
}
/// Samples the gradient at position `t`. Requires `0.0 ≤ t ≤ 1.0`.
pub fn eval_continuous(&self, t: f64) -> Color {
let t = t.max(0.0).min(1.0);
self.eval.eval_continuous(t as f32)
}
}
pub(crate) trait EvalGradient {
fn name(&self) -> &'static str;
fn eval_rational(&self, i: usize, n: usize) -> Color {
if n <= 1 {
self.eval_continuous(1.0)
} else {
self.eval_continuous(i as f32 / (n - 1) as f32)
}
}
fn eval_continuous(&self, t: f32) -> Color;
}
impl Debug for Gradient {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Gradient({})", self.eval.name())
}
}