style/values/computed/
easing.rs1use euclid::approxeq::ApproxEq;
8
9use crate::bezier::Bezier;
10use crate::piecewise_linear::PiecewiseLinearFunction;
11use crate::values::computed::{Integer, Number};
12use crate::values::generics::easing::{self, BeforeFlag, StepPosition, TimingKeyword};
13
14pub type ComputedTimingFunction = easing::TimingFunction<Integer, Number, PiecewiseLinearFunction>;
16
17pub type TimingFunction = ComputedTimingFunction;
19
20impl ComputedTimingFunction {
21 fn calculate_step_output(
22 steps: i32,
23 pos: StepPosition,
24 progress: f64,
25 before_flag: BeforeFlag,
26 ) -> f64 {
27 let mut current_step = (progress * (steps as f64)).floor() as i32;
30
31 if pos == StepPosition::Start
33 || pos == StepPosition::JumpStart
34 || pos == StepPosition::JumpBoth
35 {
36 current_step = current_step.checked_add(1).unwrap_or(current_step);
37 }
38
39 if before_flag == BeforeFlag::Set
42 && (progress * steps as f64).rem_euclid(1.0).approx_eq(&0.0)
43 {
44 current_step = current_step.checked_sub(1).unwrap_or(current_step);
45 }
46
47 if progress >= 0.0 && current_step < 0 {
51 current_step = 0;
52 }
53
54 let jumps = if pos == StepPosition::JumpBoth {
56 steps.checked_add(1).unwrap_or(steps)
57 } else if pos == StepPosition::JumpNone {
58 steps.checked_sub(1).unwrap_or(steps)
59 } else {
60 steps
61 };
62
63 if progress <= 1.0 && current_step > jumps {
64 current_step = jumps;
65 }
66
67 (current_step as f64) / (jumps as f64)
68 }
69
70 pub fn calculate_output(&self, progress: f64, before_flag: BeforeFlag, epsilon: f64) -> f64 {
72 let progress = match self {
73 TimingFunction::CubicBezier { x1, y1, x2, y2 } => {
74 Bezier::calculate_bezier_output(progress, epsilon, *x1, *y1, *x2, *y2)
75 },
76 TimingFunction::Steps(steps, pos) => {
77 Self::calculate_step_output(*steps, *pos, progress, before_flag)
78 },
79 TimingFunction::LinearFunction(function) => function.at(progress as f32).into(),
80 TimingFunction::Keyword(keyword) => match keyword {
81 TimingKeyword::Linear => progress,
82 TimingKeyword::Ease => {
83 Bezier::calculate_bezier_output(progress, epsilon, 0.25, 0.1, 0.25, 1.)
84 },
85 TimingKeyword::EaseIn => {
86 Bezier::calculate_bezier_output(progress, epsilon, 0.42, 0., 1., 1.)
87 },
88 TimingKeyword::EaseOut => {
89 Bezier::calculate_bezier_output(progress, epsilon, 0., 0., 0.58, 1.)
90 },
91 TimingKeyword::EaseInOut => {
92 Bezier::calculate_bezier_output(progress, epsilon, 0.42, 0., 0.58, 1.)
93 },
94 },
95 };
96
97 progress.min(f64::MAX).max(f64::MIN)
108 }
109}