veloren/voxygen/src/audio/fader.rs

63 lines
1.5 KiB
Rust
Raw Normal View History

2019-08-31 08:30:23 +00:00
#[derive(PartialEq, Clone, Copy)]
pub struct Fader {
length: f32,
running_time: f32,
volume_from: f32,
volume_to: f32,
2019-09-05 09:11:18 +00:00
is_running: bool,
2019-08-31 08:30:23 +00:00
}
fn lerp(t: f32, a: f32, b: f32) -> f32 { (1.0 - t) * a + t * b }
2019-08-31 08:30:23 +00:00
impl Fader {
pub fn fade(time: f32, volume_from: f32, volume_to: f32) -> Self {
Self {
length: time,
running_time: 0.0,
volume_from,
volume_to,
is_running: true,
}
}
pub fn fade_in(time: f32) -> Self {
Self {
length: time,
running_time: 0.0,
volume_from: 0.0,
volume_to: 1.0,
is_running: true,
}
}
pub fn fade_out(time: f32, volume_from: f32) -> Self {
2019-08-31 08:30:23 +00:00
Self {
length: time,
running_time: 0.0,
volume_from,
2019-08-31 08:30:23 +00:00
volume_to: 0.0,
is_running: true,
}
}
pub fn update(&mut self, dt: f32) {
if self.is_running {
self.running_time = self.running_time + dt;
if self.running_time >= self.length {
self.running_time = self.length;
self.is_running = false;
}
}
}
pub fn get_volume(&self) -> f32 {
2019-09-05 09:11:18 +00:00
lerp(
self.running_time / self.length,
self.volume_from,
self.volume_to,
)
2019-08-31 08:30:23 +00:00
}
pub fn is_finished(&self) -> bool { self.running_time >= self.length || !self.is_running }
2019-08-31 08:30:23 +00:00
}