trackball/touch.rs
1use crate::float;
2use core::fmt::Debug;
3use glam::Vec2;
4
5/// Touch gestures inducing slide, orbit, scale, and focus.
6///
7/// Implements [`Default`] and can be created with `Touch::default()`. Recognizes up to `N` fingers,
8/// ten by default.
9///
10/// All methods except [`Self::fingers()`] must be invoked on matching events fired by your 3D
11/// graphics library of choice.
12#[derive(Debug, Clone, Default)]
13pub struct Touch<F: Debug + Eq, const N: usize = 10> {
14 /// Finger positions of up to `N` fingers.
15 pos: Fingers<F, N>,
16 /// Cached normalization of previous two-finger vector.
17 vec: Option<(Vec2, f32)>,
18 /// Number of fingers and centroid position of potential finger tap gesture.
19 tap: Option<(usize, Vec2)>,
20 /// Number of total finger moves per potential finger tap gesture.
21 mvs: usize,
22}
23
24impl<F: Debug + Copy + Eq, const N: usize> Touch<F, N> {
25 /// Computes centroid position, roll angle, and scale ratio from finger gestures.
26 ///
27 /// Parameters are:
28 ///
29 /// * `fid` as generic finger ID like `Some(id)` for touch and `None` for mouse events,
30 /// * `pos` as current cursor/finger position in screen space,
31 /// * `mvs` as number of finger moves for debouncing potential finger tap gesture with zero
32 /// resulting in no delay of non-tap gestures while tap gesture can still be recognized. Use
33 /// zero unless tap gestures are hardly recognized.
34 ///
35 /// Returns number of fingers, centroid position, roll angle, and scale ratio in screen space in
36 /// the order mentioned or `None` when debouncing tap gesture with non-vanishing `mvs`. See
37 /// [`Self::discard()`] for tap gesture result.
38 ///
39 /// # Panics
40 ///
41 /// Panics with more than `N` fingers.
42 pub fn compute(&mut self, fid: F, pos: Vec2, mvs: usize) -> Option<(usize, Vec2, f32, f32)> {
43 // Insert or update finger position.
44 let old_pos = self.pos.insert(fid, pos).expect("Too many fingers");
45 // Ignore events of unchanged finger position.
46 if old_pos == Some(pos) {
47 return None;
48 }
49 // Current number of fingers.
50 let num = self.pos.len();
51 // Maximum number of fingers seen per potential tap.
52 let max = self.tap.map_or(1, |(tap, _pos)| tap).max(num);
53 // Centroid position.
54 #[allow(clippy::cast_precision_loss)]
55 let pos = self.pos.values().sum::<Vec2>() / num as f32;
56 // Cancel potential tap if more moves than number of finger starts plus optional number of
57 // moves per finger for debouncing tap gesture. Debouncing would delay non-tap gestures.
58 if self.mvs >= max + mvs * max {
59 // Make sure to not resume cancelled tap when fingers are discarded.
60 self.mvs = usize::MAX;
61 // Cancel potential tap.
62 self.tap = None;
63 } else {
64 // Count total moves per potential tap.
65 self.mvs += 1;
66 // Insert or update potential tap as long as fingers are not discarded.
67 if num >= max {
68 self.tap = Some((num, pos));
69 }
70 }
71 // Inhibit finger gestures for given number of moves per finger. No delay with zero `mvs`.
72 if self.mvs >= mvs * max {
73 // Identity roll angle and scale ratio.
74 let (rot, rat) = (0.0, 1.0);
75 // Roll and scale only with two-finger gesture, otherwise orbit or slide via centroid.
76 if num == 2 {
77 // Position of first and second finger.
78 let mut val = self.pos.values();
79 let one_pos = val.next().unwrap();
80 let two_pos = val.next().unwrap();
81 // Ray and its length pointing from first to second finger.
82 let new_vec = two_pos - one_pos;
83 let new_len = new_vec.length();
84 let new_ray = new_vec / new_len;
85 // Get old and replace with new vector.
86 if let Some((old_ray, old_len)) = self.vec.replace((new_ray, new_len)) {
87 // Roll angle in opposite direction at centroid.
88 let rot = float::atan2(old_ray.perp_dot(new_ray), old_ray.dot(new_ray));
89 // Scale ratio at centroid.
90 let rat = old_len / new_len;
91 // Induced two-finger slide, roll, and scale.
92 Some((num, pos, rot, rat))
93 } else {
94 // Start position of slide.
95 Some((num, pos, rot, rat))
96 }
97 } else {
98 // Induced one-finger or more than two-finger orbit or slide.
99 Some((num, pos, rot, rat))
100 }
101 } else {
102 // Gesture inhibited.
103 None
104 }
105 }
106 /// Removes finger position and returns number of fingers and centroid position of tap gesture.
107 ///
108 /// Returns `None` as long as there are finger positions or no tap gesture has been recognized.
109 ///
110 /// Discards finger positions and tap gesture if generic finger ID `fid` is unknown.
111 pub fn discard(&mut self, fid: F) -> Option<(usize, Vec2)> {
112 let unknown = self.pos.remove(fid).is_none();
113 self.vec = None;
114 if self.pos.is_empty() || unknown {
115 self.pos.clear();
116 self.mvs = 0;
117 self.tap.take().filter(|_tap| !unknown)
118 } else {
119 None
120 }
121 }
122 /// Number of fingers.
123 #[must_use]
124 pub fn fingers(&self) -> usize {
125 self.pos.len()
126 }
127}
128
129/// Finger positions of up to `N` fingers in slots filled in order.
130#[derive(Debug, Clone)]
131struct Fingers<F, const N: usize>([Option<(F, Vec2)>; N]);
132
133impl<F, const N: usize> Default for Fingers<F, N> {
134 fn default() -> Self {
135 Self([const { None }; N])
136 }
137}
138
139impl<F: Copy + Eq, const N: usize> Fingers<F, N> {
140 /// Inserts or updates finger position and returns old one or `Err` if there are no free slots.
141 fn insert(&mut self, fid: F, pos: Vec2) -> Result<Option<Vec2>, (F, Vec2)> {
142 if let Some((_fid, old_pos)) = self.0.iter_mut().flatten().find(|(id, _pos)| *id == fid) {
143 return Ok(Some(core::mem::replace(old_pos, pos)));
144 }
145 let slot = self
146 .0
147 .iter_mut()
148 .find(|slot| slot.is_none())
149 .ok_or((fid, pos))?;
150 *slot = Some((fid, pos));
151 Ok(None)
152 }
153 /// Removes finger position and returns it.
154 fn remove(&mut self, fid: F) -> Option<Vec2> {
155 let slot = self
156 .0
157 .iter_mut()
158 .find(|slot| slot.is_some_and(|(id, _pos)| id == fid))?;
159 slot.take().map(|(_fid, pos)| pos)
160 }
161 /// Removes all finger positions.
162 const fn clear(&mut self) {
163 self.0 = [None; N];
164 }
165 /// Finger positions in slot order.
166 fn values(&self) -> impl Iterator<Item = Vec2> {
167 self.0.iter().flatten().map(|&(_fid, pos)| pos)
168 }
169 /// Number of fingers.
170 fn len(&self) -> usize {
171 self.values().count()
172 }
173 /// Whether there are no fingers.
174 fn is_empty(&self) -> bool {
175 self.0.iter().all(Option::is_none)
176 }
177}