Skip to main content

strata_render/
orbit_controls.rs

1//! OrbitControls: Interactive 3D Camera Controller with Spherical Kinematics, Panning, and Damping.
2//!
3//! Provides mouse/touch orbit rotation, screen-space camera plane panning,
4//! and geometric zooming with pole gimbal-lock prevention.
5
6use crate::math3d::{Mat4, Vec3};
7use crate::scene3d::Camera3D;
8
9/// Active mouse or pointer drag interaction mode.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum OrbitInteractionMode {
12    #[default]
13    None,
14    Rotate,
15    Pan,
16    Zoom,
17}
18
19/// Interactive 3D Camera Orbit Controller.
20#[derive(Debug, Clone, PartialEq)]
21pub struct OrbitControls {
22    // Current spherical coordinates
23    pub radius: f32,
24    pub phi: f32,
25    pub theta: f32,
26    pub target: Vec3,
27
28    // Target spherical coordinates for damping / inertia
29    target_radius: f32,
30    target_phi: f32,
31    target_theta: f32,
32    target_center: Vec3,
33
34    // Limits and tuning
35    pub min_distance: f32,
36    pub max_distance: f32,
37    pub min_polar_angle: f32,
38    pub max_polar_angle: f32,
39    pub rotate_speed: f32,
40    pub zoom_speed: f32,
41    pub pan_speed: f32,
42    pub enable_damping: bool,
43    pub damping_factor: f32,
44
45    // Pointer interaction tracking
46    pub active_mode: OrbitInteractionMode,
47    last_pointer_x: f32,
48    last_pointer_y: f32,
49}
50
51impl Default for OrbitControls {
52    fn default() -> Self {
53        Self::new_with_target_and_eye(Vec3::ZERO, Vec3::new(0.0, 2.0, 5.0))
54    }
55}
56
57impl OrbitControls {
58    /// Creates OrbitControls initialized from target focus point and camera eye position.
59    pub fn new_with_target_and_eye(target: Vec3, eye: Vec3) -> Self {
60        let offset = eye - target;
61        let radius = offset.length().max(0.1);
62        let phi = if radius > 1e-5 {
63            (offset.y / radius).clamp(-1.0, 1.0).acos()
64        } else {
65            std::f32::consts::FRAC_PI_2
66        };
67        let theta = offset.x.atan2(offset.z);
68
69        Self {
70            radius,
71            phi,
72            theta,
73            target,
74            target_radius: radius,
75            target_phi: phi,
76            target_theta: theta,
77            target_center: target,
78            min_distance: 0.2,
79            max_distance: 2000.0,
80            min_polar_angle: 0.01,
81            max_polar_angle: std::f32::consts::PI - 0.01,
82            rotate_speed: 1.0,
83            zoom_speed: 1.0,
84            pan_speed: 1.0,
85            enable_damping: true,
86            damping_factor: 0.1,
87            active_mode: OrbitInteractionMode::None,
88            last_pointer_x: 0.0,
89            last_pointer_y: 0.0,
90        }
91    }
92
93    /// Initializes OrbitControls from an existing Camera3D.
94    pub fn from_camera(camera: &Camera3D) -> Self {
95        match camera {
96            Camera3D::Perspective {
97                position, target, ..
98            }
99            | Camera3D::Orthographic {
100                position, target, ..
101            } => {
102                let eye = Vec3::new(position[0], position[1], position[2]);
103                let tgt = Vec3::new(target[0], target[1], target[2]);
104                Self::new_with_target_and_eye(tgt, eye)
105            }
106        }
107    }
108
109    /// Computes the current 3D eye position in Cartesian coordinates.
110    #[inline]
111    pub fn eye_position(&self) -> Vec3 {
112        let sin_phi = self.phi.sin();
113        let cos_phi = self.phi.cos();
114        let sin_theta = self.theta.sin();
115        let cos_theta = self.theta.cos();
116
117        Vec3::new(
118            self.target.x + self.radius * sin_phi * sin_theta,
119            self.target.y + self.radius * cos_phi,
120            self.target.z + self.radius * sin_phi * cos_theta,
121        )
122    }
123
124    /// Rotates azimuthal (theta) and polar (phi) angles by given deltas.
125    pub fn rotate_by(&mut self, delta_theta: f32, delta_phi: f32) {
126        self.target_theta += delta_theta * self.rotate_speed;
127        self.target_phi = (self.target_phi + delta_phi * self.rotate_speed)
128            .clamp(self.min_polar_angle, self.max_polar_angle);
129
130        if !self.enable_damping {
131            self.theta = self.target_theta;
132            self.phi = self.target_phi;
133        }
134    }
135
136    /// Zooms camera radius by multiplicative factor or wheel delta.
137    pub fn zoom_delta(&mut self, delta: f32) {
138        let factor = 1.0 - delta * 0.1 * self.zoom_speed;
139        self.target_radius =
140            (self.target_radius * factor).clamp(self.min_distance, self.max_distance);
141
142        if !self.enable_damping {
143            self.radius = self.target_radius;
144        }
145    }
146
147    /// Pans camera target point in screen-space camera plane.
148    pub fn pan_by(
149        &mut self,
150        delta_x: f32,
151        delta_y: f32,
152        viewport_width: f32,
153        viewport_height: f32,
154        fov_degrees: f32,
155    ) {
156        let eye = self.eye_position();
157        let forward = (self.target - eye).normalize();
158        let right = forward.cross(Vec3::UP).normalize();
159        let up = right.cross(forward).normalize();
160
161        let fov_rad = fov_degrees.to_radians();
162        let factor = 2.0 * self.radius * (fov_rad * 0.5).tan();
163        let dx = (-delta_x / viewport_width.max(1.0))
164            * factor
165            * (viewport_width / viewport_height.max(1.0))
166            * self.pan_speed;
167        let dy = (delta_y / viewport_height.max(1.0)) * factor * self.pan_speed;
168
169        let pan_offset = right * dx + up * dy;
170        self.target_center = self.target_center + pan_offset;
171
172        if !self.enable_damping {
173            self.target = self.target_center;
174        }
175    }
176
177    // --- Pointer Input Event Handlers ---
178
179    /// Handles pointer down: button 0 = rotate, 1 = zoom, 2 = pan.
180    pub fn on_pointer_down(&mut self, x: f32, y: f32, button: u8) {
181        self.last_pointer_x = x;
182        self.last_pointer_y = y;
183        self.active_mode = match button {
184            0 => OrbitInteractionMode::Rotate,
185            1 => OrbitInteractionMode::Zoom,
186            2 => OrbitInteractionMode::Pan,
187            _ => OrbitInteractionMode::Rotate,
188        };
189    }
190
191    /// Handles pointer move: computes screen deltas and applies appropriate transformation.
192    pub fn on_pointer_move(
193        &mut self,
194        x: f32,
195        y: f32,
196        viewport_w: f32,
197        viewport_h: f32,
198        fov_degrees: f32,
199    ) {
200        if self.active_mode == OrbitInteractionMode::None {
201            return;
202        }
203
204        let dx = x - self.last_pointer_x;
205        let dy = y - self.last_pointer_y;
206        self.last_pointer_x = x;
207        self.last_pointer_y = y;
208
209        match self.active_mode {
210            OrbitInteractionMode::Rotate => {
211                let delta_theta = -dx * (2.0 * std::f32::consts::PI / viewport_w.max(1.0));
212                let delta_phi = -dy * (std::f32::consts::PI / viewport_h.max(1.0));
213                self.rotate_by(delta_theta, delta_phi);
214            }
215            OrbitInteractionMode::Pan => {
216                self.pan_by(dx, dy, viewport_w, viewport_h, fov_degrees);
217            }
218            OrbitInteractionMode::Zoom => {
219                self.zoom_delta(dy * 0.05);
220            }
221            OrbitInteractionMode::None => {}
222        }
223    }
224
225    /// Handles pointer up: releases active drag mode.
226    pub fn on_pointer_up(&mut self) {
227        self.active_mode = OrbitInteractionMode::None;
228    }
229
230    /// Handles mouse wheel zoom delta.
231    pub fn on_wheel(&mut self, wheel_delta_y: f32) {
232        self.zoom_delta(wheel_delta_y * 0.02);
233    }
234
235    /// Advances kinematic damping simulation.
236    pub fn tick(&mut self, dt: f32) {
237        if !self.enable_damping {
238            return;
239        }
240
241        let alpha = (self.damping_factor * (dt / 0.016)).clamp(0.01, 1.0);
242        self.radius += (self.target_radius - self.radius) * alpha;
243        self.phi += (self.target_phi - self.phi) * alpha;
244        self.theta += (self.target_theta - self.theta) * alpha;
245        self.target = self.target.lerp(self.target_center, alpha);
246    }
247
248    /// Writes updated eye position and target back to a Camera3D.
249    pub fn update_camera(&self, camera: &mut Camera3D) {
250        let eye = self.eye_position();
251        match camera {
252            Camera3D::Perspective {
253                position, target, ..
254            }
255            | Camera3D::Orthographic {
256                position, target, ..
257            } => {
258                *position = [eye.x, eye.y, eye.z];
259                *target = [self.target.x, self.target.y, self.target.z];
260            }
261        }
262    }
263
264    /// Computes the look-at view matrix corresponding to the current camera state.
265    pub fn view_matrix(&self) -> Mat4 {
266        Mat4::look_at(self.eye_position(), self.target, Vec3::UP)
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn test_orbit_controls_initialization() {
276        let target = Vec3::ZERO;
277        let eye = Vec3::new(0.0, 0.0, 10.0);
278        let controls = OrbitControls::new_with_target_and_eye(target, eye);
279
280        assert!((controls.radius - 10.0).abs() < 1e-4);
281        assert!((controls.phi - std::f32::consts::FRAC_PI_2).abs() < 1e-4);
282        assert!(controls.theta.abs() < 1e-4);
283
284        let eye_computed = controls.eye_position();
285        assert!((eye_computed.z - 10.0).abs() < 1e-4);
286    }
287
288    #[test]
289    fn test_orbit_controls_pole_clamping() {
290        let mut controls = OrbitControls::default();
291        controls.enable_damping = false;
292
293        // Try rotating past north pole (phi < 0)
294        controls.rotate_by(0.0, -100.0);
295        assert!(controls.phi >= controls.min_polar_angle);
296
297        // Try rotating past south pole (phi > PI)
298        controls.rotate_by(0.0, 100.0);
299        assert!(controls.phi <= controls.max_polar_angle);
300    }
301
302    #[test]
303    fn test_orbit_controls_zoom_limits() {
304        let mut controls = OrbitControls::default();
305        controls.enable_damping = false;
306
307        // Zoom in to minimum limit
308        for _ in 0..100 {
309            controls.zoom_delta(5.0);
310        }
311        assert!(controls.radius >= controls.min_distance);
312
313        // Zoom out to maximum limit
314        for _ in 0..100 {
315            controls.zoom_delta(-5.0);
316        }
317        assert!(controls.radius <= controls.max_distance);
318    }
319
320    #[test]
321    fn test_orbit_controls_pan_shifts_target() {
322        let mut controls = OrbitControls::default();
323        controls.enable_damping = false;
324        let orig_target = controls.target;
325
326        controls.pan_by(50.0, 0.0, 800.0, 600.0, 60.0);
327        assert_ne!(controls.target, orig_target);
328    }
329}