Skip to main content

trackball/
orbit.rs

1use glam::{Quat, Vec2, Vec3};
2
3#[cfg(not(feature = "cc"))]
4use crate::{Image, float};
5
6/// Orbit induced by displacement on screen.
7///
8/// Implements [`Default`] and can be created with `Orbit::default()`.
9///
10/// Both its methods must be invoked on matching events fired by your 3D graphics library of choice.
11#[derive(Debug, Clone, Default)]
12pub struct Orbit {
13    /// Caches trackball point of previous cursor/finger position.
14    exp: Option<Vec3>,
15}
16
17#[cfg(not(feature = "cc"))]
18use core::f32::consts::FRAC_PI_2;
19
20impl Orbit {
21    /// Computes rotation between previous and current cursor/finger position.
22    ///
23    /// Trackball point of previous position is cached and has to be discarded on button/finger
24    /// release via [`Self::discard()`]. Current position `pos` is clamped between origin and
25    /// maximum position `max` as screen's width and height.
26    ///
27    /// Maps positions via the exponential map onto a target-centered trackball with radius of
28    /// maximum of the screen's width and height divided by π and rotates along the shortest arc
29    /// between their trackball points so that the trackball's point under the cursor/finger stays
30    /// under it. Positions in screen corners beyond the trackball's border are mapped beyond its
31    /// equator.
32    ///
33    /// Screen space with origin in top left corner:
34    ///
35    ///   * x-axis from left to right,
36    ///   * y-axis from top to bottom.
37    ///
38    /// Camera space with origin at its target, the trackball's center:
39    ///
40    ///   * x-axis from left to right,
41    ///   * y-axis from bottom to top,
42    ///   * z-axis from far to near.
43    ///
44    /// Returns `None`:
45    ///
46    ///   * on first invocation and after [`Self::discard()`] as there is no previous position yet,
47    ///   * for displacements resulting in the same trackball point, e.g., when a position event
48    ///     fires twice.
49    #[cfg(not(feature = "cc"))]
50    pub fn compute(&mut self, pos: Vec2, max: Vec2) -> Option<Quat> {
51        // Clamped cursor/finger position from left to right and top to bottom.
52        let pos = Image::clamp_pos_wrt_max(pos, max);
53        // Centered cursor/finger position and its maximum from left to right and bottom to top.
54        let (pos, max) = Image::transform_pos_and_max_wrt_max(pos, max);
55        // Trackball's radius mapping maximum of half the screen's width or height onto quarter of
56        // its circumference.
57        let rad = max.x.max(max.y) / FRAC_PI_2;
58        // Polar angle of position, beyond equator for screen corners.
59        let pol = pos.length() / rad;
60        // Exponential map of position onto trackball.
61        let (ray, (sin, cos)) = (pos.normalize_or_zero(), float::sin_cos(pol));
62        let exp = (ray * sin).extend(cos);
63        // Get old and replace with new trackball point unless they coincide.
64        let old = self.exp.replace(exp).filter(|&old| old != exp)?;
65        // Shortest arc from new to old trackball point as rotation of camera which in turn carries
66        // old to new trackball point, keeping it under the cursor/finger.
67        let rot = exp
68            .cross(old)
69            .extend(1.0 + exp.dot(old))
70            .try_normalize()
71            .map_or_else(
72                // Shortest arc is ambiguous for antipodal trackball points as any half turn about
73                // an axis orthogonal to them carries one onto the other. Choose the half turn on
74                // the great circle through the pole as if displacing straight through the screen's
75                // center.
76                || Quat::from_xyzw(ray.y, -ray.x, 0.0, 0.0),
77                Quat::from_vec4,
78            );
79        Some(rot)
80    }
81    /// Computes rotation between previous and current cursor/finger position.
82    ///
83    /// Trackball point of previous position is cached and has to be discarded on button/finger
84    /// release via [`Self::discard()`]. Current position `pos` is clamped between origin and
85    /// maximum position `max` as screen's width and height.
86    ///
87    /// Maps positions via the exponential map onto a target-centered trackball with radius of
88    /// maximum of the screen's width and height divided by π and rotates along the shortest arc
89    /// between their trackball points so that the trackball's point under the cursor/finger stays
90    /// under it. Positions in screen corners beyond the trackball's border are mapped beyond its
91    /// equator.
92    ///
93    /// Screen space with origin in top left corner:
94    ///
95    ///   * x-axis from left to right,
96    ///   * y-axis from top to bottom.
97    ///
98    /// Camera space with origin at its target, the trackball's center:
99    ///
100    ///   * x-axis from left to right,
101    ///   * y-axis from bottom to top,
102    ///   * z-axis from far to near.
103    ///
104    /// Returns `None`:
105    ///
106    ///   * on first invocation and after [`Self::discard()`] as there is no previous position yet,
107    ///   * for displacements resulting in the same trackball point, e.g., when a position event
108    ///     fires twice.
109    #[cfg(feature = "cc")]
110    pub fn compute(&mut self, pos: Vec2, max: Vec2) -> Option<Quat> {
111        let mut rot = Quat::IDENTITY.to_array();
112        let mut old = self.exp.map_or([0.0; 4], |exp| exp.extend(1.0).to_array());
113        let (pos, max) = (pos.to_array(), max.to_array());
114        #[allow(unsafe_code)]
115        unsafe {
116            trackball_orbit_f(
117                rot.as_mut_ptr(),
118                old.as_mut_ptr(),
119                pos.as_ptr(),
120                max.as_ptr(),
121            );
122        }
123        let [x, y, z, _len] = old;
124        self.exp = Some(Vec3::new(x, y, z));
125        #[allow(clippy::float_cmp)]
126        (rot != Quat::IDENTITY.to_array()).then(|| Quat::from_array(rot))
127    }
128    /// Discards cached trackball point of previous cursor/finger position on button/finger
129    /// release.
130    pub const fn discard(&mut self) {
131        self.exp = None;
132    }
133}
134
135#[cfg(feature = "cc")]
136#[allow(unsafe_code)]
137unsafe extern "C" {
138    fn trackball_orbit_f(xyzw: *mut f32, xyzm: *mut f32, xy: *const f32, wh: *const f32);
139}