orbit-camera 0.1.2

Third-person orbit/follow camera with pitch-scaled distance, smooth following and geometry clipping
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
#![deny(missing_docs)]
//! A third-person orbit camera.
//!
//! The camera orbits a focus point that smoothly follows a target. Yaw and
//! pitch are controlled directly; the orbit distance scales with pitch (looking
//! down pulls the camera in, looking up pushes it out) and can be zoomed. The
//! focus point and distance interpolate frame-rate independently. An optional
//! clipping pass pulls the camera in when geometry blocks the line of sight to
//! the focus.
//!
//! The camera produces geometry (eye, focus, up) and projection parameters; it
//! does not depend on any matrix type. Build the view-projection matrix with
//! whatever math library the renderer uses.
//!
//! ```
//! use ga3::Vector;
//! use orbit_camera::OrbitCamera;
//!
//! let mut camera = OrbitCamera::new(Vector::new(0.0, 0.0, 0.0));
//! camera.rotate([0.02, 0.0]);
//! camera.follow(Vector::new(1.0, 0.0, 0.0), 1.0 / 60.0);
//! let view = camera.view();
//! let _eye = view.eye;
//! ```

use collide_ray::Ray;
use ga3::{Rotor, Vector};
use inner_space::InnerSpace;

/// A source of geometry the camera can clip against.
///
/// Implemented for any collision world that can cast a ray and return the
/// distance to the nearest hit within `max_distance`. With the `collide-mesh`
/// feature this is implemented for [`collide_mesh::CollisionWorld`].
pub trait Clip {
    /// Casts `ray` and returns the distance to the nearest hit no farther than
    /// `max_distance`, or `None` if nothing is hit.
    fn raycast(&self, ray: &Ray<Vector<f32>>, max_distance: f32) -> Option<f32>;
}

#[cfg(feature = "collide-mesh")]
impl Clip for collide_mesh::CollisionWorld {
    fn raycast(&self, ray: &Ray<Vector<f32>>, max_distance: f32) -> Option<f32> {
        collide_mesh::CollisionWorld::raycast(self, ray, max_distance)
    }
}

/// Tunable parameters of an [`OrbitCamera`].
///
/// [`CameraConfig::default`] matches a Zelda-style action-adventure camera. Each
/// field can be overridden for a different feel.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct CameraConfig {
    /// Lowest pitch in radians (looking up the most). Negative looks up.
    pub min_pitch: f32,
    /// Highest pitch in radians (looking down the most).
    pub max_pitch: f32,
    /// Orbit distance at `min_pitch`.
    pub low_distance: f32,
    /// Orbit distance at `max_pitch`.
    pub high_distance: f32,
    /// Distance the camera never clips below.
    pub min_distance: f32,
    /// Smallest zoom multiplier.
    pub min_zoom: f32,
    /// Largest zoom multiplier.
    pub max_zoom: f32,
    /// Multiplicative zoom step applied per unit of [`OrbitCamera::zoom`] input.
    pub zoom_step: f32,
    /// Height of the focus point above the followed target.
    pub focus_height: f32,
    /// Smoothing strength of the focus point. Larger follows faster.
    pub focus_strength: f32,
    /// Smoothing strength of the orbit distance. Larger reaches the goal faster.
    pub distance_strength: f32,
    /// Distance below which clipping is skipped.
    pub clip_start: f32,
    /// Gap kept between the camera and clipped geometry.
    pub clip_margin: f32,
    /// Initial pitch of a freshly created camera.
    pub default_pitch: f32,
    /// Vertical field of view in radians.
    pub field_of_view: f32,
    /// Near clip plane.
    pub near_plane: f32,
    /// Far clip plane.
    pub far_plane: f32,
}

impl Default for CameraConfig {
    fn default() -> Self {
        Self {
            min_pitch: -0.524,
            max_pitch: 1.047,
            low_distance: 4.0,
            high_distance: 9.0,
            min_distance: 1.0,
            min_zoom: 0.5,
            max_zoom: 2.0,
            zoom_step: 0.2,
            focus_height: 1.5,
            focus_strength: 4.0,
            distance_strength: 8.0,
            clip_start: 0.5,
            clip_margin: 0.2,
            default_pitch: 0.4,
            field_of_view: std::f32::consts::FRAC_PI_3,
            near_plane: 0.1,
            far_plane: 200.0,
        }
    }
}

/// The horizontal movement basis derived from the camera yaw.
///
/// Both vectors lie in the ground plane, so movement input stays level
/// regardless of pitch.
#[derive(Copy, Clone, Debug)]
pub struct MovementBasis {
    /// Direction the camera faces, projected onto the ground plane.
    pub forward: Vector<f32>,
    /// Direction to the camera's right, projected onto the ground plane.
    pub right: Vector<f32>,
}

/// Everything needed to build a view-projection matrix.
#[derive(Copy, Clone, Debug)]
pub struct ViewParameters {
    /// Camera position.
    pub eye: Vector<f32>,
    /// Point the camera looks at.
    pub focus: Vector<f32>,
    /// Up direction. World +Y by default, or the aligned surface normal after
    /// [`OrbitCamera::align_up`].
    pub up: Vector<f32>,
    /// Vertical field of view in radians.
    pub field_of_view: f32,
    /// Near clip plane.
    pub near_plane: f32,
    /// Far clip plane.
    pub far_plane: f32,
}

/// A third-person camera that orbits a smoothly following focus point.
#[derive(Copy, Clone, Debug)]
pub struct OrbitCamera {
    yaw: f32,
    pitch: f32,
    zoom_factor: f32,
    distance: f32,
    focus: Vector<f32>,
    rotation: Rotor<f32>,
    config: CameraConfig,
}

const IDENTITY: Rotor<f32> = Rotor {
    scalar: 1.0,
    xy: 0.0,
    xz: 0.0,
    yz: 0.0,
};

fn rotation_between(from: Vector<f32>, to: Vector<f32>) -> Rotor<f32> {
    (from + to) * from
}

impl OrbitCamera {
    /// Creates a camera looking at `target` from the default yaw.
    pub fn new(target: Vector<f32>) -> Self {
        Self::facing(target, 0.0, CameraConfig::default())
    }

    /// Creates a camera looking at `target` from `yaw`, with `config`.
    pub fn facing(target: Vector<f32>, yaw: f32, config: CameraConfig) -> Self {
        let mut camera = Self {
            yaw,
            pitch: config.default_pitch,
            zoom_factor: 1.0,
            distance: 0.0,
            focus: target + Vector::y(config.focus_height),
            rotation: IDENTITY,
            config,
        };
        camera.distance = camera.goal_distance();
        camera
    }

    /// Returns the configuration.
    pub fn config(&self) -> &CameraConfig {
        &self.config
    }

    /// Replaces the configuration. The next [`follow`](Self::follow) eases the
    /// camera toward the new distance.
    pub fn set_config(&mut self, config: CameraConfig) {
        self.config = config;
    }

    /// Rotates the camera by `[yaw, pitch]` deltas in radians. Pitch is clamped
    /// to the configured range.
    pub fn rotate(&mut self, delta: [f32; 2]) {
        let [delta_yaw, delta_pitch] = delta;
        self.yaw -= delta_yaw;
        self.pitch = (self.pitch - delta_pitch).clamp(self.config.min_pitch, self.config.max_pitch);
    }

    /// Current yaw in radians.
    pub fn yaw(&self) -> f32 {
        self.yaw
    }

    /// Sets the yaw directly in radians. Use this when the consumer drives the
    /// orientation absolutely (spherical coordinates, snap-to-step yaw) instead
    /// of through [`rotate`](Self::rotate) deltas.
    pub fn set_yaw(&mut self, yaw: f32) {
        self.yaw = yaw;
    }

    /// Current pitch in radians.
    pub fn pitch(&self) -> f32 {
        self.pitch
    }

    /// Sets the pitch directly in radians, clamped to the configured range.
    pub fn set_pitch(&mut self, pitch: f32) {
        self.pitch = pitch.clamp(self.config.min_pitch, self.config.max_pitch);
    }

    /// Current focus point.
    pub fn focus(&self) -> Vector<f32> {
        self.focus
    }

    /// Sets the focus point directly, bypassing the easing in
    /// [`follow`](Self::follow). Use this when the consumer drives the look-at
    /// target itself (cutscenes, custom focus logic).
    pub fn set_focus(&mut self, focus: Vector<f32>) {
        self.focus = focus;
    }

    /// Current orbit distance from the focus point to the eye.
    pub fn distance(&self) -> f32 {
        self.distance
    }

    /// Sets the orbit distance directly, bypassing the easing in
    /// [`follow`](Self::follow). Use this to drive the distance from a custom
    /// model (absolute zoom, aim modes) or a custom clip pass.
    pub fn set_distance(&mut self, distance: f32) {
        self.distance = distance;
    }

    /// Current up direction. World +Y until [`align_up`](Self::align_up) tilts
    /// the orbit frame toward a surface normal.
    pub fn up(&self) -> Vector<f32> {
        self.rotation.rotate(Vector::y(1.0))
    }

    /// The orbit orientation rotor mapping the local +Y-up frame into world
    /// space. Identity keeps the classic world-up camera.
    pub fn rotation(&self) -> Rotor<f32> {
        self.rotation
    }

    /// Sets the orbit orientation rotor directly. Use [`align_up`](Self::align_up)
    /// for incremental tilting that preserves the yaw frame.
    pub fn set_rotation(&mut self, rotation: Rotor<f32>) {
        self.rotation = rotation;
    }

    /// Tilts the orbit frame so its up axis matches `target_up`, taking the
    /// shortest path from the current up. Yaw and pitch keep their meaning
    /// relative to the tilted frame, so walking across a planet does not snap
    /// the camera (parallel transport, no pole singularity). `target_up` need
    /// not be normalized.
    pub fn align_up(&mut self, target_up: Vector<f32>) {
        if target_up.magnitude2() < 1e-12 {
            return;
        }
        let current = self.up();
        let target = target_up.normalize();
        if (current + target).magnitude2() < 1e-6 {
            return;
        }
        self.rotation = (self.rotation * rotation_between(current, target)).normalize();
    }

    /// Zooms by `amount`. Positive zooms in. Clamped to the configured range.
    pub fn zoom(&mut self, amount: f32) {
        self.zoom_factor = (self.zoom_factor * (-amount * self.config.zoom_step).exp2())
            .clamp(self.config.min_zoom, self.config.max_zoom);
    }

    /// Eases the focus point toward `target` and the orbit distance toward its
    /// pitch-derived goal, frame-rate independently over `timestep` seconds.
    pub fn follow(&mut self, target: Vector<f32>, timestep: f32) {
        let goal_focus = target + self.rotation.rotate(Vector::y(self.config.focus_height));
        self.focus +=
            (goal_focus - self.focus) * timed_friction(self.config.focus_strength, timestep);

        let goal_distance = self.goal_distance();
        self.distance += (goal_distance - self.distance)
            * timed_friction(self.config.distance_strength, timestep);
    }

    /// Pulls the camera in if `world` blocks the line of sight from the focus
    /// point to the eye.
    pub fn clip<C: Clip>(&mut self, world: &C) {
        if self.distance <= self.config.clip_start {
            return;
        }
        let direction = (self.eye() - self.focus) / self.distance;
        let ray = Ray::new(self.focus + direction * self.config.clip_start, direction);
        if let Some(hit) = world.raycast(&ray, self.distance - self.config.clip_start) {
            let clipped = (self.config.clip_start + hit - self.config.clip_margin)
                .max(self.config.min_distance);
            if clipped < self.distance {
                self.distance = clipped;
            }
        }
    }

    /// Current eye position.
    pub fn eye(&self) -> Vector<f32> {
        self.eye_at(self.distance)
    }

    /// Eye position the camera would have at an arbitrary orbit `distance`,
    /// using the current yaw, pitch and focus. Useful for custom clip passes
    /// that probe a candidate distance before committing it via
    /// [`set_distance`](Self::set_distance).
    pub fn eye_at(&self, distance: f32) -> Vector<f32> {
        let (sin_pitch, cos_pitch) = self.pitch.sin_cos();
        let (sin_yaw, cos_yaw) = self.yaw.sin_cos();
        let local = Vector::new(cos_pitch * sin_yaw, sin_pitch, cos_pitch * cos_yaw);
        self.focus + self.rotation.rotate(local) * distance
    }

    /// Eases the yaw toward `look_direction` (projected onto the ground plane),
    /// frame-rate independently. Useful for lock-on steering. `strength`
    /// controls how fast.
    pub fn steer_toward(&mut self, look_direction: Vector<f32>, strength: f32, timestep: f32) {
        use std::f32::consts::{PI, TAU};
        let length = look_direction.x.hypot(look_direction.z);
        if length < 1e-4 {
            return;
        }
        let target_yaw = (-look_direction.x).atan2(-look_direction.z);
        let difference = (target_yaw - self.yaw + PI).rem_euclid(TAU) - PI;
        self.yaw += difference * timed_friction(strength, timestep);
    }

    /// Forward direction projected onto the tangent plane perpendicular to the
    /// current [`up`](Self::up).
    pub fn forward_xz(&self) -> Vector<f32> {
        self.rotation
            .rotate(Vector::new(-self.yaw.sin(), 0.0, -self.yaw.cos()))
    }

    /// Right direction projected onto the tangent plane perpendicular to the
    /// current [`up`](Self::up).
    pub fn right_xz(&self) -> Vector<f32> {
        self.rotation
            .rotate(Vector::new(self.yaw.cos(), 0.0, -self.yaw.sin()))
    }

    /// The horizontal movement basis for character input.
    pub fn basis(&self) -> MovementBasis {
        MovementBasis {
            forward: self.forward_xz(),
            right: self.right_xz(),
        }
    }

    /// The parameters needed to build a view-projection matrix.
    pub fn view(&self) -> ViewParameters {
        ViewParameters {
            eye: self.eye(),
            focus: self.focus,
            up: self.up(),
            field_of_view: self.config.field_of_view,
            near_plane: self.config.near_plane,
            far_plane: self.config.far_plane,
        }
    }

    fn goal_distance(&self) -> f32 {
        let pitch_ratio =
            (self.pitch - self.config.min_pitch) / (self.config.max_pitch - self.config.min_pitch);
        (self.config.low_distance
            + (self.config.high_distance - self.config.low_distance) * pitch_ratio)
            * self.zoom_factor
    }
}

fn timed_friction(strength: f32, timestep: f32) -> f32 {
    1.0 - (-strength * timestep).exp2()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn eye_sits_above_and_behind_focus() {
        let camera = OrbitCamera::new(Vector::new(0.0, 0.0, 0.0));
        let offset = camera.eye() - camera.focus();
        let length = (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z).sqrt();
        assert!(length > 0.0);
        assert!(offset.y > 0.0);
    }

    #[test]
    fn rotate_clamps_pitch() {
        let mut camera = OrbitCamera::new(Vector::new(0.0, 0.0, 0.0));
        camera.rotate([0.0, 100.0]);
        assert!((camera.pitch() - camera.config().min_pitch).abs() < 1e-5);
        camera.rotate([0.0, -100.0]);
        assert!((camera.pitch() - camera.config().max_pitch).abs() < 1e-5);
    }

    #[test]
    fn follow_moves_focus_toward_target() {
        let mut camera = OrbitCamera::new(Vector::new(0.0, 0.0, 0.0));
        let start = camera.focus();
        camera.follow(Vector::new(10.0, 0.0, 0.0), 1.0 / 60.0);
        assert!(camera.focus().x > start.x);
        assert!(camera.focus().x < 10.0);
    }

    #[test]
    fn set_focus_and_distance_bypass_easing() {
        let mut camera = OrbitCamera::new(Vector::new(0.0, 0.0, 0.0));
        let focus = Vector::new(3.0, 1.0, -2.0);
        camera.set_focus(focus);
        camera.set_distance(5.0);
        assert_eq!(camera.focus(), focus);
        assert_eq!(camera.distance(), 5.0);
    }

    #[test]
    fn set_yaw_is_absolute_and_set_pitch_clamps() {
        let mut camera = OrbitCamera::new(Vector::new(0.0, 0.0, 0.0));
        camera.set_yaw(1.25);
        assert_eq!(camera.yaw(), 1.25);
        camera.set_pitch(100.0);
        assert!((camera.pitch() - camera.config().max_pitch).abs() < 1e-6);
    }

    #[test]
    fn eye_at_matches_eye_for_current_distance() {
        let camera = OrbitCamera::new(Vector::new(1.0, 2.0, 3.0));
        let eye = camera.eye();
        let probed = camera.eye_at(camera.distance());
        assert!((eye - probed).x.abs() < 1e-6);
        assert!((eye - probed).y.abs() < 1e-6);
        assert!((eye - probed).z.abs() < 1e-6);
    }

    #[test]
    fn default_camera_has_world_up() {
        let up = OrbitCamera::new(Vector::new(0.0, 0.0, 0.0)).up();
        assert!(up.x.abs() < 1e-6);
        assert!((up.y - 1.0).abs() < 1e-6);
        assert!(up.z.abs() < 1e-6);
    }

    #[test]
    fn rotation_between_maps_from_onto_to() {
        let from = Vector::new(0.0, 1.0, 0.0);
        let to = Vector::new(1.0, 0.0, 0.0);
        let mapped = rotation_between(from, to).rotate(from);
        assert!((to - mapped).x.abs() < 1e-5);
        assert!((to - mapped).y.abs() < 1e-5);
        assert!((to - mapped).z.abs() < 1e-5);
    }

    #[test]
    fn align_up_matches_target_normal() {
        let mut camera = OrbitCamera::new(Vector::new(0.0, 0.0, 0.0));
        let normal = Vector::new(1.0, 1.0, 0.0);
        camera.align_up(normal);
        let up = camera.up();
        let scale = 1.0 / normal.magnitude();
        assert!((up.x - normal.x * scale).abs() < 1e-4);
        assert!((up.y - normal.y * scale).abs() < 1e-4);
        assert!((up.z - normal.z * scale).abs() < 1e-4);
    }

    #[test]
    fn incremental_align_tracks_up_in_every_plane() {
        for (axis_a, axis_b, name) in [(0, 1, "xy"), (1, 2, "yz"), (0, 2, "xz")] {
            let mut camera = OrbitCamera::new(Vector::new(0.0, 0.0, 0.0));
            for step in 1..=200 {
                let angle = step as f32 / 200.0 * 2.0;
                let mut components = [0.0f32; 3];
                components[axis_b] = angle.cos();
                components[axis_a] = angle.sin();
                let target = Vector::new(components[0], components[1], components[2]);
                camera.align_up(target);
                let up = camera.up();
                let alignment = up.x * target.x + up.y * target.y + up.z * target.z;
                assert!(
                    alignment > 0.999,
                    "plane {name}: up diverged at step {step}: dot {alignment}, up ({}, {}, {}) target ({}, {}, {})",
                    up.x,
                    up.y,
                    up.z,
                    target.x,
                    target.y,
                    target.z,
                );
            }
        }
    }

    #[test]
    fn eye_keeps_orbit_distance_after_align() {
        let mut camera = OrbitCamera::new(Vector::new(0.0, 0.0, 0.0));
        camera.align_up(Vector::new(0.3, 0.5, 0.8));
        let offset = camera.eye() - camera.focus();
        let length = (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z).sqrt();
        assert!((length - camera.distance()).abs() < 1e-4);
    }
}