Skip to main content

trackball/
image.rs

1use crate::{Frame, Rigid, Scope};
2use glam::{Mat4, Vec2, Vec3};
3
4/// Image as projection of [`Scope`] wrt [`Frame`].
5#[derive(Debug, Clone, Copy, PartialEq)]
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7#[cfg_attr(
8    feature = "rkyv-08",
9    derive(rkyv_08::Archive, rkyv_08::Serialize, rkyv_08::Deserialize),
10    rkyv(crate = rkyv_08)
11)]
12pub struct Image {
13    /// Current position in screen space of hovering input or pointing device.
14    pos: Vec2,
15    /// Maximum position in screen space as screen's width and height.
16    max: Vec2,
17    /// Cached unit per pixel on focus plane to scale/project positions/vectors onto focus plane.
18    upp: f32,
19    /// Cached previous frame or `None` to recompute view.
20    frame: Option<Frame>,
21    /// Cached previous scope or `None` to recompute projection.
22    scope: Option<Scope>,
23    /// Cached view transformation from camera to world space or inversely if passive.
24    view_rigid: Rigid,
25    /// Cached homogeneous view matrix computed from view transformation.
26    view_mat: Mat4,
27    /// Cached scale-identical orthographic or perspective projection matrix.
28    proj_mat: Mat4,
29    /// Cached transformation.
30    proj_view_mat: Mat4,
31    /// Cached inverse of transformation.
32    proj_view_inv: Mat4,
33    /// Whether to compute transformation. Default is `true`.
34    compute_mat: bool,
35    /// Whether to compute inverse transformation. Default is `true`.
36    compute_inv: bool,
37    /// Whether to use passive transformations. Default is `false`.
38    use_passive: bool,
39}
40
41impl Image {
42    /// Computes initial transformations from frame, scope, and screen's width and height.
43    #[must_use]
44    pub fn new(frame: Frame, scope: Scope, max: Vec2) -> Self {
45        let mut image = Self {
46            pos: Vec2::ZERO,
47            max,
48            upp: 0.0,
49            frame: None,
50            scope: None,
51            view_rigid: Rigid::IDENTITY,
52            view_mat: Mat4::ZERO,
53            proj_mat: Mat4::ZERO,
54            proj_view_mat: Mat4::ZERO,
55            proj_view_inv: Mat4::ZERO,
56            compute_mat: true,
57            compute_inv: true,
58            use_passive: false,
59        };
60        if frame.distance() != 0.0 {
61            image.compute(frame, scope);
62        }
63        image
64    }
65    /// Recomputes only cached matrices whose parameters have changed, see [`Self::set_compute()`].
66    ///
67    /// Returns `Some(true)` on success, `Some(false)` on failure, and `None` with no changes.
68    pub fn compute(&mut self, frame: Frame, scope: Scope) -> Option<bool> {
69        let new_view = self.frame != Some(frame);
70        let new_projection = self.frame.map(|frame| frame.distance()) != Some(frame.distance())
71            || self.scope != Some(scope);
72        self.frame = Some(frame);
73        self.scope = Some(scope);
74        if new_view {
75            self.view_rigid = if self.use_passive {
76                frame.inverse_view()
77            } else {
78                frame.view()
79            };
80            self.view_mat = self.view_rigid.into();
81        }
82        if new_projection {
83            (self.proj_mat, self.upp) = scope.projection_and_upp(frame.distance(), self.max);
84        }
85        (new_view || new_projection).then(|| {
86            if self.compute_mat || self.compute_inv {
87                self.proj_view_mat = self.proj_mat * self.view_mat;
88            }
89            if self.compute_inv {
90                let det = self.proj_view_mat.determinant();
91                let inv = det != 0.0 && det.is_finite();
92                if inv {
93                    self.proj_view_inv = self.proj_view_mat.inverse();
94                }
95                inv
96            } else {
97                true
98            }
99        })
100    }
101    /// Sets whether to compute transformation and inverse transformation with [`Self::compute()`].
102    ///
103    /// Default is `(true, true)`. Takes effect with next [`Self::compute()`].
104    pub const fn set_compute(&mut self, compute_mat: bool, compute_inv: bool) {
105        // Let `Self::compute()` recompute transformations by invalidating cached previous scope.
106        if self.compute_mat != compute_mat || self.compute_inv != compute_inv {
107            self.scope = None;
108        }
109        self.compute_mat = compute_mat;
110        self.compute_inv = compute_inv;
111    }
112    /// Sets whether to use passive transformations.
113    ///
114    /// Default is `false`. Takes effect with next [`Self::compute()`].
115    pub const fn set_passive(&mut self, use_passive: bool) {
116        // Let `Self::compute()` recompute view by invalidating cached previous frame.
117        if self.use_passive != use_passive {
118            self.frame = None;
119        }
120        self.use_passive = use_passive;
121    }
122    /// Current position in screen space of hovering input or pointing device.
123    #[must_use]
124    pub const fn pos(&self) -> Vec2 {
125        self.pos
126    }
127    /// Sets current position in screen space of hovering input or pointing device.
128    pub const fn set_pos(&mut self, pos: Vec2) {
129        self.pos = pos;
130    }
131    /// Maximum position in screen space as screen's width and height.
132    #[must_use]
133    pub const fn max(&self) -> Vec2 {
134        self.max
135    }
136    /// Sets maximum position in screen space as screen's width and height.
137    ///
138    /// Takes effect with next [`Self::compute()`].
139    pub fn set_max(&mut self, max: Vec2) {
140        // Let `Self::compute()` recompute projection by invalidating cached previous scope.
141        if self.max != max {
142            self.scope = None;
143        }
144        self.max = max;
145    }
146    /// Cached unit per pixel on focus plane to scale/project positions/vectors onto focus plane.
147    #[must_use]
148    pub const fn upp(&self) -> f32 {
149        self.upp
150    }
151    /// Cached view transformation from camera to world space or inversely if passive.
152    ///
153    /// See [`Self::set_passive()`].
154    #[must_use]
155    pub const fn view_rigid(&self) -> Rigid {
156        self.view_rigid
157    }
158    /// Cached view matrix.
159    #[must_use]
160    pub const fn view(&self) -> Mat4 {
161        self.view_mat
162    }
163    /// Cached projection matrix.
164    #[must_use]
165    pub const fn projection(&self) -> Mat4 {
166        self.proj_mat
167    }
168    /// Cached projection view matrix.
169    #[must_use]
170    pub const fn transformation(&self) -> Mat4 {
171        self.proj_view_mat
172    }
173    /// Cached inverse projection view matrix.
174    #[must_use]
175    pub const fn inverse_transformation(&self) -> Mat4 {
176        self.proj_view_inv
177    }
178    /// Clamps position in screen space wrt its maximum in screen space.
179    #[must_use]
180    pub const fn clamp_pos_wrt_max(pos: Vec2, max: Vec2) -> Vec2 {
181        Vec2::new(pos.x.clamp(0.0, max.x), pos.y.clamp(0.0, max.y))
182    }
183    /// Clamps position in screen space.
184    #[must_use]
185    pub const fn clamp_pos(&self, pos: Vec2) -> Vec2 {
186        Self::clamp_pos_wrt_max(pos, self.max)
187    }
188    /// Transforms position and its maximum from screen to camera space wrt its maximum.
189    #[must_use]
190    pub fn transform_pos_and_max_wrt_max(pos: Vec2, max: Vec2) -> (Vec2, Vec2) {
191        let max = max * 0.5;
192        (Vec2::new(pos.x - max.x, max.y - pos.y), max)
193    }
194    /// Transforms position from screen to camera space.
195    #[must_use]
196    pub fn transform_pos(&self, pos: Vec2) -> Vec2 {
197        Self::transform_pos_and_max_wrt_max(pos, self.max).0
198    }
199    /// Transforms vector from screen to camera space.
200    #[must_use]
201    pub const fn transform_vec(vec: Vec2) -> Vec2 {
202        Vec2::new(vec.x, -vec.y)
203    }
204    /// Transforms position from screen to camera space and projects it onto focus plane.
205    #[must_use]
206    pub fn project_pos(&self, pos: Vec2) -> Vec3 {
207        (self.transform_pos(pos) * self.upp).extend(0.0)
208    }
209    /// Transforms vector from screen to camera space and projects it onto focus plane.
210    #[must_use]
211    pub fn project_vec(&self, vec: Vec2) -> Vec3 {
212        (Self::transform_vec(vec) * self.upp).extend(0.0)
213    }
214}