veloren_voxygen/hud/
change_notification.rs1use serde::{Deserialize, Serialize};
2
3use std::time::Duration;
4
5const NOTIF_START_ALPHA: f32 = 1.0;
7
8const NOTIF_LIFETIME: f32 = 2.0;
10const NOTIF_FADETIME: f32 = 1.5;
12
13#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
16pub enum NotificationReason {
17 Remind = 2,
18 Enable = 1,
19 #[serde(other)]
20 Disable = 0,
21}
22#[derive(Default)]
25pub struct ChangeNotification {
26 pub reason: Option<NotificationReason>,
27 pub alpha: f32,
28 lifetime: Duration,
29 fadetime: Duration,
30 initial_fadetime: Duration,
31}
32
33impl ChangeNotification {
34 pub fn new(
35 reason: Option<NotificationReason>,
36 alpha: f32,
37 lifetime: Duration,
38 fadetime: Duration,
39 ) -> Result<Self, Duration> {
40 if fadetime.is_zero() {
41 Err(fadetime)
42 } else {
43 Ok(Self {
44 reason,
45 alpha,
46 lifetime,
47 fadetime,
48 initial_fadetime: fadetime,
49 })
50 }
51 }
52
53 pub fn from_reason(reason: NotificationReason) -> Self {
54 ChangeNotification::new(
55 Some(reason),
56 NOTIF_START_ALPHA,
57 Duration::from_secs_f32(NOTIF_LIFETIME),
58 Duration::from_secs_f32(NOTIF_FADETIME),
59 )
60 .unwrap()
61 }
62
63 pub fn from_state(state: bool) -> Self {
64 ChangeNotification::from_reason(match state {
65 true => NotificationReason::Enable,
66 false => NotificationReason::Disable,
67 })
68 }
69
70 pub fn update(&mut self, dt: Duration) {
71 if self.reason.is_some() {
72 if !self.lifetime.is_zero() {
74 self.lifetime = self.lifetime.saturating_sub(dt);
75 } else if !self.fadetime.is_zero() {
77 self.fadetime = self.fadetime.saturating_sub(dt);
78 self.alpha = self.fadetime.as_secs_f32() / self.initial_fadetime.as_secs_f32();
80 } else {
82 self.reason = None;
83 }
84 }
85 }
86}