adi_clock/
pulse.rs

1// Aldaron's Device Interface / Clock
2// Copyright (c) 2017 Jeron Lau <jeron.lau@plopgrizzly.com>
3// Licensed under the MIT LICENSE
4//
5// src/pulse.rs
6
7use std::f32;
8
9/// Call these functions on the return value of Clock::since().  Use `rate_spr`
10/// to specify how many seconds it takes to cycle through the animation.
11pub trait Pulse {
12	/// Returns a number between 0-1. This function is used for animations.
13	/// It will take rate_spr seconds to go from 0 to 1. 
14	fn pulse_half_linear(&self, rate_spr: f32) -> f32;
15
16	/// Returns a number between 0-1. This function is used for animations.
17	/// It will take rate_spr seconds to go from 0 to 1 and back to 0.
18	fn pulse_full_linear(&self, rate_spr: f32) -> f32;
19
20	/// Returns a number between 0-1. This function is used for animations.
21	/// It will take rate_spr seconds to go from 0 to 1 and back to 0. It
22	/// uses cosine underneath to make the animation look smooth, by making
23	/// the beginning and end of the animation slower than the middle.
24	fn pulse_full_smooth(&self, rate_spr: f32) -> f32;
25
26	/// Returns a number between 0-1. This function is used for animations.
27	/// It will take rate_spr seconds to go from 0 to 1. It uses cosine
28	/// underneath to make the animation look smooth, by making the
29	/// beginning and end of the animation slower than the middle.
30	fn pulse_half_smooth(&self, rate_spr: f32) -> f32;
31}
32
33impl Pulse for f32 {
34	fn pulse_half_linear(&self, rate_spr: f32) -> f32 {
35		(self % rate_spr) / rate_spr
36	}
37
38	fn pulse_full_linear(&self, rate_spr: f32) -> f32 {
39		let rtn = (self % rate_spr) / (rate_spr / 2.0);
40		if rtn > 1.0 {
41			2.0 - rtn
42		}else{
43			rtn
44		}
45	}
46
47	fn pulse_full_smooth(&self, rate_spr: f32) -> f32 {
48		1.0 - (((self.pulse_full_linear(rate_spr) * f32::consts::PI)
49			.cos() + 1.0) / 2.0)
50	}
51
52	fn pulse_half_smooth(&self, rate_spr: f32) -> f32 {
53		1.0 - (((self.pulse_half_linear(rate_spr) * f32::consts::PI)
54			.cos() + 1.0) / 2.0)
55	}
56}