rg3d_ui/curve/
key.rs

1use crate::core::{
2    algebra::Vector2,
3    curve::{Curve, CurveKey, CurveKeyKind},
4    uuid::Uuid,
5};
6use std::cmp::Ordering;
7
8#[derive(Clone, Debug)]
9pub struct CurveKeyView {
10    pub position: Vector2<f32>,
11    pub kind: CurveKeyKind,
12    pub id: Uuid,
13}
14
15impl From<&CurveKey> for CurveKeyView {
16    fn from(key: &CurveKey) -> Self {
17        Self {
18            position: Vector2::new(key.location(), key.value),
19            kind: key.kind.clone(),
20            id: key.id,
21        }
22    }
23}
24
25#[derive(Clone)]
26pub struct KeyContainer {
27    keys: Vec<CurveKeyView>,
28}
29
30impl From<&Curve> for KeyContainer {
31    fn from(curve: &Curve) -> Self {
32        Self {
33            keys: curve
34                .keys()
35                .iter()
36                .map(CurveKeyView::from)
37                .collect::<Vec<_>>(),
38        }
39    }
40}
41
42impl KeyContainer {
43    pub fn add(&mut self, key: CurveKeyView) {
44        self.keys.push(key)
45    }
46
47    pub fn remove(&mut self, id: Uuid) -> Option<CurveKeyView> {
48        if let Some(position) = self.keys.iter().position(|k| k.id == id) {
49            Some(self.keys.remove(position))
50        } else {
51            None
52        }
53    }
54
55    pub fn key_ref(&self, id: Uuid) -> Option<&CurveKeyView> {
56        self.keys.iter().find(|k| k.id == id)
57    }
58
59    pub fn key_mut(&mut self, id: Uuid) -> Option<&mut CurveKeyView> {
60        self.keys.iter_mut().find(|k| k.id == id)
61    }
62
63    pub fn key_index_ref(&self, index: usize) -> Option<&CurveKeyView> {
64        self.keys.get(index)
65    }
66
67    pub fn key_index_mut(&mut self, index: usize) -> Option<&mut CurveKeyView> {
68        self.keys.get_mut(index)
69    }
70
71    pub fn keys(&self) -> &[CurveKeyView] {
72        &self.keys
73    }
74
75    pub fn keys_mut(&mut self) -> &mut [CurveKeyView] {
76        &mut self.keys
77    }
78
79    pub fn sort_keys(&mut self) {
80        self.keys.sort_by(|a, b| {
81            if a.position.x < b.position.x {
82                Ordering::Less
83            } else if a.position.x > b.position.x {
84                Ordering::Greater
85            } else {
86                Ordering::Equal
87            }
88        })
89    }
90
91    pub fn curve(&self) -> Curve {
92        Curve::from(
93            self.keys
94                .iter()
95                .map(|k| CurveKey::new(k.position.x, k.position.y, k.kind.clone()))
96                .collect::<Vec<_>>(),
97        )
98    }
99}