use viewport_lib_types::camera::{Camera, Projection};
use super::orbit::orbit_in_mode;
use crate::input::NavigationMode;
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum Easing {
Linear,
EaseOutCubic,
EaseInOutCubic,
}
impl Easing {
pub fn eval(self, t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
match self {
Self::Linear => t,
Self::EaseOutCubic => {
let inv = 1.0 - t;
1.0 - inv * inv * inv
}
Self::EaseInOutCubic => {
if t < 0.5 {
4.0 * t * t * t
} else {
let p = -2.0 * t + 2.0;
1.0 - p * p * p / 2.0
}
}
}
}
}
#[derive(Clone, Debug)]
pub struct CameraDamping {
pub orbit: f32,
pub pan: f32,
pub zoom: f32,
pub epsilon: f32,
}
impl Default for CameraDamping {
fn default() -> Self {
Self {
orbit: 0.85,
pan: 0.85,
zoom: 0.85,
epsilon: 0.0001,
}
}
}
#[derive(Clone, Debug)]
struct CameraFlight {
start_centre: glam::DVec3,
start_distance: f32,
start_orientation: glam::Quat,
#[allow(dead_code)]
start_projection: Projection,
target_centre: glam::DVec3,
target_distance: f32,
target_orientation: glam::Quat,
target_projection: Option<Projection>,
duration: f32,
elapsed: f32,
easing: Easing,
}
pub struct CameraAnimator {
damping: CameraDamping,
navigation_mode: NavigationMode,
orbit_velocity: glam::Vec2,
pan_velocity: glam::Vec2,
zoom_velocity: f32,
flight: Option<CameraFlight>,
}
impl CameraAnimator {
pub fn new(damping: CameraDamping) -> Self {
Self {
damping,
navigation_mode: NavigationMode::Arcball,
orbit_velocity: glam::Vec2::ZERO,
pan_velocity: glam::Vec2::ZERO,
zoom_velocity: 0.0,
flight: None,
}
}
pub fn with_default_damping() -> Self {
Self::new(CameraDamping::default())
}
pub fn with_navigation_mode(mut self, mode: NavigationMode) -> Self {
self.navigation_mode = mode;
self
}
pub fn set_navigation_mode(&mut self, mode: NavigationMode) {
self.navigation_mode = mode;
}
pub fn navigation_mode(&self) -> NavigationMode {
self.navigation_mode
}
pub fn apply_orbit(&mut self, yaw_delta: f32, pitch_delta: f32) {
if self.flight.is_some() {
self.flight = None;
}
self.orbit_velocity += glam::Vec2::new(yaw_delta, pitch_delta);
}
pub fn apply_pan(&mut self, right_delta: f32, up_delta: f32) {
if self.flight.is_some() {
self.flight = None;
}
self.pan_velocity += glam::Vec2::new(right_delta, up_delta);
}
pub fn apply_zoom(&mut self, delta: f32) {
if self.flight.is_some() {
self.flight = None;
}
self.zoom_velocity += delta;
}
pub fn fly_to(
&mut self,
camera: &Camera,
target_centre: impl Into<glam::DVec3>,
target_distance: f32,
target_orientation: glam::Quat,
duration: f32,
) {
self.fly_to_full(
camera,
target_centre,
target_distance,
target_orientation,
None,
duration,
Easing::EaseOutCubic,
);
}
pub fn fly_to_with_easing(
&mut self,
camera: &Camera,
target_centre: impl Into<glam::DVec3>,
target_distance: f32,
target_orientation: glam::Quat,
duration: f32,
easing: Easing,
) {
self.fly_to_full(
camera,
target_centre,
target_distance,
target_orientation,
None,
duration,
easing,
);
}
#[allow(clippy::too_many_arguments)]
pub fn fly_to_full(
&mut self,
camera: &Camera,
target_centre: impl Into<glam::DVec3>,
target_distance: f32,
target_orientation: glam::Quat,
target_projection: Option<Projection>,
duration: f32,
easing: Easing,
) {
self.orbit_velocity = glam::Vec2::ZERO;
self.pan_velocity = glam::Vec2::ZERO;
self.zoom_velocity = 0.0;
self.flight = Some(CameraFlight {
start_centre: camera.target(),
start_distance: camera.focus_distance(),
start_orientation: camera.orientation(),
start_projection: camera.projection,
target_centre: target_centre.into(),
target_distance,
target_orientation,
target_projection,
duration: duration.max(0.001),
elapsed: 0.0,
easing,
});
}
pub fn cancel_flight(&mut self) {
self.flight = None;
}
pub fn destination(&self, camera: &Camera) -> Camera {
let mut out = camera.clone();
if let Some(flight) = &self.flight {
out.set_orbit(
flight.target_centre,
flight
.target_distance
.clamp(Camera::MIN_DISTANCE, Camera::MAX_DISTANCE),
flight.target_orientation.normalize(),
);
if let Some(proj) = flight.target_projection {
out.projection = proj;
}
}
out
}
pub fn is_animating(&self) -> bool {
if self.flight.is_some() {
return true;
}
let eps = self.damping.epsilon;
self.orbit_velocity.length() > eps
|| self.pan_velocity.length() > eps
|| self.zoom_velocity.abs() > eps
}
pub fn update(&mut self, dt: f32, camera: &mut Camera) -> bool {
if let Some(ref mut flight) = self.flight {
flight.elapsed += dt;
let raw_t = (flight.elapsed / flight.duration).min(1.0);
let t = flight.easing.eval(raw_t);
let distance =
flight.start_distance + (flight.target_distance - flight.start_distance) * t;
camera.set_orbit(
flight.start_centre.lerp(flight.target_centre, f64::from(t)),
distance.clamp(Camera::MIN_DISTANCE, Camera::MAX_DISTANCE),
flight
.start_orientation
.slerp(flight.target_orientation, t)
.normalize(),
);
if raw_t >= 1.0 {
if let Some(proj) = flight.target_projection {
camera.projection = proj;
}
self.flight = None;
}
return true;
}
let eps = self.damping.epsilon;
let mut changed = false;
let mut target = camera.orbit_target();
if self.orbit_velocity.length() > eps {
let (step, decay) = coast_step(self.damping.orbit, dt);
let turn = self.orbit_velocity * step;
orbit_in_mode(&mut target, self.navigation_mode, turn.x, turn.y);
self.orbit_velocity *= decay;
if self.orbit_velocity.length() <= eps {
self.orbit_velocity = glam::Vec2::ZERO;
}
changed = true;
}
if self.pan_velocity.length() > eps {
let (step, decay) = coast_step(self.damping.pan, dt);
target.pan_world(self.pan_velocity.x * step, -self.pan_velocity.y * step);
self.pan_velocity *= decay;
if self.pan_velocity.length() <= eps {
self.pan_velocity = glam::Vec2::ZERO;
}
changed = true;
}
if self.zoom_velocity.abs() > eps {
let (step, decay) = coast_step(self.damping.zoom, dt);
target.zoom_by_delta(self.zoom_velocity * step);
self.zoom_velocity *= decay;
if self.zoom_velocity.abs() <= eps {
self.zoom_velocity = 0.0;
}
changed = true;
}
if changed {
camera.set_orbit_target(target);
}
changed
}
}
fn coast_step(damping: f32, dt: f32) -> (f32, f32) {
let decay = damping.powf(dt * 60.0);
let step = if damping < 1.0 {
(1.0 - decay) / (1.0 - damping)
} else {
dt * 60.0
};
(step, decay)
}
#[cfg(test)]
mod tests {
use super::*;
fn default_camera() -> Camera {
Camera::default()
}
#[test]
fn test_damping_decays_velocity() {
let mut anim = CameraAnimator::with_default_damping();
let mut cam = default_camera();
anim.apply_orbit(0.5, 0.3);
assert!(anim.is_animating());
for _ in 0..300 {
anim.update(1.0 / 60.0, &mut cam);
}
assert!(!anim.is_animating(), "should have settled after 300 frames");
}
#[test]
fn test_zero_damping_passes_through() {
let damping = CameraDamping {
orbit: 0.0,
pan: 0.0,
zoom: 0.0,
epsilon: 0.0001,
};
let mut anim = CameraAnimator::new(damping);
let mut cam = default_camera();
let orig_orientation = cam.orientation();
anim.apply_orbit(0.1, 0.0);
anim.update(1.0 / 60.0, &mut cam);
assert!(
!anim.is_animating(),
"zero damping should settle in one frame"
);
assert!(
(cam.orientation().x - orig_orientation.x).abs() > 1e-6
|| (cam.orientation().y - orig_orientation.y).abs() > 1e-6,
"camera orientation should have changed"
);
}
#[test]
fn test_fly_to_reaches_target() {
let mut anim = CameraAnimator::with_default_damping();
let mut cam = default_camera();
let target_centre = glam::Vec3::new(10.0, 20.0, 30.0);
let target_dist = 15.0;
let target_orient = glam::Quat::from_rotation_y(std::f32::consts::PI);
anim.fly_to(&cam, target_centre, target_dist, target_orient, 0.5);
for _ in 0..120 {
anim.update(1.0 / 60.0, &mut cam);
}
assert!(
(cam.target() - target_centre.as_dvec3()).length() < 1e-4,
"centre should match target: {:?}",
cam.target()
);
assert!(
(cam.focus_distance() - target_dist).abs() < 1e-4,
"distance should match target: {}",
cam.focus_distance()
);
}
#[test]
fn destination_without_flight_is_the_camera() {
let anim = CameraAnimator::with_default_damping();
let cam = default_camera();
let dest = anim.destination(&cam);
assert_eq!(dest, cam);
}
#[test]
fn destination_mid_flight_is_where_the_flight_lands() {
let mut anim = CameraAnimator::with_default_damping();
let mut cam = default_camera();
let target_orient = glam::Quat::from_rotation_z(1.2) * glam::Quat::from_rotation_x(0.4);
let ortho = cam.projection.to_orthographic(12.0);
anim.fly_to_full(
&cam,
glam::Vec3::new(3.0, -2.0, 5.0),
12.0,
target_orient,
Some(ortho),
0.5,
Easing::EaseInOutCubic,
);
for _ in 0..10 {
anim.update(1.0 / 60.0, &mut cam);
}
assert!(anim.is_animating(), "flight should still be under way");
let dest = anim.destination(&cam);
assert!(
cam.orientation().angle_between(target_orient) > 0.1,
"the camera should be part-way, not at the target"
);
for _ in 0..60 {
anim.update(1.0 / 60.0, &mut cam);
}
assert!(!anim.is_animating());
assert!((dest.target() - cam.target()).length() < 1e-4);
assert!((dest.focus_distance() - cam.focus_distance()).abs() < 1e-4);
assert!(dest.orientation().angle_between(cam.orientation()) < 1e-3);
assert_eq!(dest.projection, cam.projection);
assert_eq!(dest.projection, ortho);
}
#[test]
fn test_fly_to_cancelled_by_input() {
let mut anim = CameraAnimator::with_default_damping();
let mut cam = default_camera();
let target = glam::Vec3::new(100.0, 0.0, 0.0);
anim.fly_to(&cam, target, 50.0, glam::Quat::IDENTITY, 1.0);
for _ in 0..5 {
anim.update(1.0 / 60.0, &mut cam);
}
anim.apply_orbit(0.1, 0.0);
anim.update(1.0 / 60.0, &mut cam);
assert!(
(cam.target() - target.as_dvec3()).length() > 1.0,
"flight should have been cancelled"
);
}
#[test]
fn test_is_animating_reflects_state() {
let mut anim = CameraAnimator::with_default_damping();
let mut cam = default_camera();
assert!(!anim.is_animating());
anim.apply_zoom(1.0);
assert!(anim.is_animating());
for _ in 0..300 {
anim.update(1.0 / 60.0, &mut cam);
}
assert!(!anim.is_animating());
}
#[test]
fn test_easing_boundaries() {
for easing in [Easing::Linear, Easing::EaseOutCubic, Easing::EaseInOutCubic] {
let v0 = easing.eval(0.0);
let v1 = easing.eval(1.0);
assert!(v0.abs() < 1e-6, "{easing:?}: eval(0) = {v0}, expected 0");
assert!(
(v1 - 1.0).abs() < 1e-6,
"{easing:?}: eval(1) = {v1}, expected 1"
);
}
}
fn pan_coast(hz: f32) -> f32 {
let mut anim = CameraAnimator::with_default_damping();
let mut cam = default_camera();
let start = cam.target();
anim.apply_pan(0.1, 0.0);
for _ in 0..(hz as usize * 10) {
anim.update(1.0 / hz, &mut cam);
}
(cam.target() - start).length() as f32
}
#[test]
fn coast_distance_does_not_depend_on_frame_rate() {
let at_60 = pan_coast(60.0);
assert!(
(at_60 - 0.1 / (1.0 - 0.85)).abs() < 1e-3,
"60 Hz coast={at_60}"
);
for hz in [30.0, 120.0, 144.0, 240.0] {
let coast = pan_coast(hz);
assert!(
(coast - at_60).abs() < 1e-3,
"{hz} Hz coast={coast}, 60 Hz coast={at_60}"
);
}
}
#[test]
fn fly_coast_turns_about_the_eye() {
let look = crate::LookAngles::new(0.3, -0.4).orientation();
let mut cam = Camera::orbit(glam::DVec3::ZERO, 5.0, look);
let eye = cam.eye();
let mut anim =
CameraAnimator::with_default_damping().with_navigation_mode(NavigationMode::Fly);
anim.apply_orbit(0.2, 0.15);
for _ in 0..600 {
anim.update(1.0 / 60.0, &mut cam);
}
assert!((cam.eye() - eye).length() < 1e-3, "the eye moved");
let mut arcball_cam = Camera::orbit(glam::DVec3::ZERO, 5.0, look);
let mut arcball = CameraAnimator::with_default_damping();
arcball.apply_orbit(0.2, 0.15);
for _ in 0..600 {
arcball.update(1.0 / 60.0, &mut arcball_cam);
}
assert!((arcball_cam.eye() - eye).length() > 0.1);
}
#[test]
fn turntable_coast_stops_at_the_pole_limit() {
let mut cam = Camera::orbit(
glam::DVec3::ZERO,
5.0,
crate::LookAngles::new(0.0, -1.3).orientation(),
);
let mut anim =
CameraAnimator::with_default_damping().with_navigation_mode(NavigationMode::Turntable);
anim.apply_orbit(0.0, 0.5);
for _ in 0..600 {
anim.update(1.0 / 60.0, &mut cam);
}
let eye_elevation = (cam.orientation() * glam::Vec3::Z).z.asin();
assert!(
eye_elevation < 89.0_f32.to_radians() + 1e-3,
"elevation={eye_elevation}"
);
}
#[test]
fn arcball_is_the_default_mode() {
assert_eq!(
CameraAnimator::with_default_damping().navigation_mode(),
NavigationMode::Arcball
);
}
}