use core::f32::consts::FRAC_PI_2;
use glam::{DVec3, Vec3};
use crate::camera::{Camera, Projection};
use crate::cull::Aabb;
pub const PITCH_LIMIT: f32 = FRAC_PI_2 - 0.05;
pub const MIN_DISTANCE: f32 = 0.01;
pub const MAX_DISTANCE: f32 = 1.0e6;
pub const FRAME_MARGIN: f32 = 1.1;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct OrbitCamera {
pivot: Vec3,
distance: f32,
yaw: f32,
pitch: f32,
fov_y: f32,
near: f32,
}
impl OrbitCamera {
#[must_use]
pub fn new(pivot: Vec3, distance: f32, projection: Projection) -> Self {
let Projection::Perspective { fov_y, near } = projection else {
panic!("an orbit camera is perspective-only, got {projection:?}");
};
assert!(
distance.is_finite(),
"the orbit distance must be finite, got {distance}"
);
assert!(near > 0.0, "the near plane must be positive, got {near}");
assert!(
fov_y > 0.0 && fov_y < core::f32::consts::PI,
"the field of view must be in (0, π), got {fov_y}"
);
Self {
pivot,
distance: distance.clamp(MIN_DISTANCE, MAX_DISTANCE),
yaw: 0.0,
pitch: 0.0,
fov_y,
near,
}
}
#[must_use]
pub const fn pivot(&self) -> Vec3 {
self.pivot
}
#[must_use]
pub const fn distance(&self) -> f32 {
self.distance
}
pub fn orbit(&mut self, yaw: f32, pitch: f32) {
assert!(
yaw.is_finite() && pitch.is_finite(),
"orbit deltas must be finite, got yaw {yaw} and pitch {pitch}"
);
self.yaw += yaw;
self.pitch = (self.pitch + pitch).clamp(-PITCH_LIMIT, PITCH_LIMIT);
}
pub fn pan(&mut self, right: f32, up: f32) {
assert!(
right.is_finite() && up.is_finite(),
"pan deltas must be finite, got right {right} and up {up}"
);
let (right_axis, up_axis) = self.basis();
self.pivot += (right_axis * right + up_axis * up) * self.viewport_height();
}
pub fn zoom(&mut self, delta: f32) {
assert!(
delta.is_finite(),
"the zoom delta must be finite, got {delta}"
);
self.distance = (self.distance * (-delta).exp()).clamp(MIN_DISTANCE, MAX_DISTANCE);
}
pub fn frame(&mut self, bounds: Aabb, aspect: f32) {
assert!(
aspect.is_finite() && aspect > 0.0,
"aspect ratio must be finite and positive, got {aspect}"
);
assert!(
bounds.min.is_finite() && bounds.max.is_finite(),
"the framed bounds must be finite, got {bounds:?}"
);
let radius = bounds.half_extent().length();
let half_fov_y = 0.5 * self.fov_y;
let half_fov_x = (half_fov_y.tan() * aspect).atan();
let half_fov = half_fov_y.min(half_fov_x);
self.pivot = bounds.center();
self.distance = (radius * FRAME_MARGIN / half_fov.sin())
.max(self.near + radius)
.clamp(MIN_DISTANCE, MAX_DISTANCE);
}
#[must_use]
pub fn camera(&self) -> Camera {
Camera {
eye: self.pivot + self.direction() * self.distance,
target: self.pivot,
up: Vec3::Y,
projection: Projection::Perspective {
fov_y: self.fov_y,
near: self.near,
},
}
}
#[must_use]
pub fn walk_direction(yaw: f64, ahead: f64, strafe: f64) -> DVec3 {
let (sin, cos) = yaw.sin_cos();
let along = DVec3::new(-sin, 0.0, -cos);
let right = DVec3::new(cos, 0.0, -sin);
(along * ahead + right * strafe).normalize_or_zero()
}
fn direction(&self) -> Vec3 {
let (sin_yaw, cos_yaw) = self.yaw.sin_cos();
let (sin_pitch, cos_pitch) = self.pitch.sin_cos();
Vec3::new(sin_yaw * cos_pitch, sin_pitch, cos_yaw * cos_pitch)
}
fn basis(&self) -> (Vec3, Vec3) {
let forward = -self.direction();
let right = forward.cross(Vec3::Y).normalize();
(right, right.cross(forward))
}
fn viewport_height(&self) -> f32 {
2.0 * self.distance * (0.5 * self.fov_y).tan()
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::f32::consts::FRAC_PI_2;
const ASPECT: f32 = 16.0 / 9.0;
fn orbit_camera() -> OrbitCamera {
OrbitCamera::new(Vec3::new(1.0, 2.0, -3.0), 5.0, Projection::default())
}
fn right_of(camera: &Camera) -> Vec3 {
(camera.target - camera.eye)
.normalize()
.cross(Vec3::Y)
.normalize()
}
#[test]
fn an_untouched_orbit_camera_matches_the_engine_default_pose() {
let orbit = OrbitCamera::new(Vec3::ZERO, 2.0, Projection::default());
assert_eq!(orbit.camera(), Camera::default());
}
#[test]
fn a_positive_yaw_delta_swings_the_eye_toward_the_cameras_own_right() {
for (turn, sign) in [(0.1f32, 1.0f32), (-0.1, -1.0)] {
for (start_yaw, start_pitch) in [(0.0f32, 0.0f32), (2.3, 0.6), (-1.1, -0.4)] {
let mut orbit = orbit_camera();
orbit.orbit(start_yaw, start_pitch);
let before = orbit.camera();
let right = right_of(&before);
orbit.orbit(turn, 0.0);
let after = orbit.camera();
let moved = (after.eye - before.eye).normalize();
let leaned = moved.dot(right);
assert!(
leaned * sign > 0.9,
"a yaw of {turn} from ({start_yaw}, {start_pitch}) moved the eye {leaned} of \
the way along the camera's own right {right:?}, and the sign says it went \
the other way"
);
assert!(
(after.eye - before.eye).length() < 0.2 * orbit.distance(),
"a yaw of {turn} moved the eye too far for the sign above to mean what it says"
);
assert_eq!(after.target, before.target, "the pivot moved");
assert!(
((after.eye - after.target).length() - (before.eye - before.target).length())
.abs()
< 1e-4,
"the distance changed"
);
}
}
}
#[test]
fn a_positive_pitch_delta_lifts_the_eye_and_aims_the_view_downward() {
for (tilt, sign) in [(0.5f32, 1.0f32), (-0.5, -1.0)] {
let mut orbit = orbit_camera();
let before = orbit.camera();
orbit.orbit(0.0, tilt);
let after = orbit.camera();
assert!(
(after.eye.y - before.eye.y) * sign > 0.0,
"a pitch of {tilt} moved the eye from {:?} to {:?}, which is the wrong way",
before.eye,
after.eye
);
let forward = (after.target - after.eye).normalize();
assert!(
forward.y * sign < 0.0,
"a pitch of {tilt} left the view looking {forward:?}, which is not back down at \
the pivot"
);
assert_eq!(after.target, before.target, "the pivot moved");
}
}
#[test]
fn the_pitch_clamp_stops_short_of_vertical_and_the_view_still_builds() {
for sign in [1.0f32, -1.0] {
let mut orbit = orbit_camera();
let mut highest = f32::NEG_INFINITY;
for step in 0..40 {
orbit.orbit(0.0, sign * 0.5);
let camera = orbit.camera();
let direction = (camera.eye - camera.target).normalize();
let elevation = direction.y * sign;
assert!(
elevation >= highest - 1e-6,
"at step {step} the eye's elevation fell from {highest} to {elevation}: it \
went over the top instead of stopping"
);
assert!(
elevation <= PITCH_LIMIT.sin() + 1e-6,
"at step {step} the eye reached an elevation of {elevation}, past the limit"
);
assert!(
camera.view().is_finite(),
"at step {step} the pose produced a NaN view matrix"
);
highest = elevation;
}
let mut orbit = orbit_camera();
orbit.orbit(0.0, sign * 10.0);
let camera = orbit.camera();
let direction = (camera.eye - camera.target).normalize();
assert!(
(direction.y * sign - PITCH_LIMIT.sin()).abs() < 1e-5,
"a ten-radian tilt left the eye at {direction:?} rather than on the limit"
);
let level = Vec3::new(direction.x, 0.0, direction.z).length();
assert!(level > 0.01, "no horizontal component left at all");
assert!(
camera.view().is_finite(),
"the clamped pose still produced a NaN view matrix"
);
}
}
#[test]
fn panning_follows_the_view_plane_rather_than_the_world_axes() {
let displace = |yaw: f32, pitch: f32| {
let mut orbit = orbit_camera();
orbit.orbit(yaw, pitch);
let before = orbit.camera();
orbit.pan(1.0, 0.0);
let after = orbit.camera();
assert!(
(after.eye - before.eye - (after.target - before.target)).length() < 1e-4,
"pan moved the eye and the pivot by different amounts"
);
(after.target - before.target, right_of(&before))
};
for pitch in [0.0f32, 0.7, -0.7] {
let (level, right) = displace(0.0, pitch);
assert!(
level.normalize().dot(right) > 0.999,
"a rightward pan moved the pivot {level:?}, not along the camera's right {right:?}"
);
assert!(
level.y.abs() < 1e-5,
"a rightward pan at pitch {pitch} changed the height by {}",
level.y
);
}
let (facing_z, _) = displace(0.0, 0.0);
let (facing_x, right) = displace(FRAC_PI_2, 0.0);
assert!(
facing_x.normalize().dot(right) > 0.999,
"after a quarter turn a rightward pan moved the pivot {facing_x:?}, not along the \
camera's new right {right:?}"
);
assert!(
facing_z.normalize().dot(facing_x.normalize()).abs() < 1e-5,
"a quarter turn left the pan direction unchanged at {facing_z:?} and {facing_x:?}, \
which is what panning in world axes looks like"
);
let mut orbit = orbit_camera();
orbit.orbit(0.0, 0.7);
let before = orbit.camera();
orbit.pan(0.0, 1.0);
let moved = orbit.camera().target - before.target;
let (_, up_axis) = orbit.basis();
assert!(
moved.normalize().dot(up_axis) > 0.999,
"an upward pan moved the pivot {moved:?}, not along the camera's up {up_axis:?}"
);
assert!(
moved.y > 0.0 && moved.dot(Vec3::Y).abs() < moved.length(),
"an upward pan from a raised eye must rise *and* travel, got {moved:?}"
);
}
#[test]
fn a_half_height_pan_moves_the_scene_exactly_half_a_screen() {
for distance in [0.5f32, 5.0, 500.0] {
let mut orbit = OrbitCamera::new(Vec3::ZERO, distance, Projection::default());
orbit.orbit(0.9, 0.4);
let was = orbit.pivot();
orbit.pan(0.0, 0.5);
let clip = orbit.camera().view_projection(ASPECT) * was.extend(1.0);
let ndc_y = clip.y / clip.w;
assert!(
(ndc_y + 1.0).abs() < 1e-4,
"at {distance} m a half-height pan put the old pivot at y = {ndc_y} in NDC, not on \
the bottom edge at -1"
);
assert!(
(clip.x / clip.w).abs() < 1e-4,
"a vertical pan moved the scene sideways"
);
}
}
#[test]
fn zoom_moves_the_eye_along_its_ray_and_leaves_the_lens_alone() {
let mut orbit = orbit_camera();
orbit.orbit(0.8, 0.3);
let before = orbit.camera();
orbit.zoom(1.0);
let after = orbit.camera();
assert!(
after.eye.distance(after.target) < before.eye.distance(before.target),
"a positive zoom delta moved the eye away from the pivot"
);
assert_eq!(after.target, before.target, "the pivot moved");
assert_eq!(after.projection, before.projection, "the lens changed");
assert!(
(after.eye - after.target)
.normalize()
.dot((before.eye - before.target).normalize())
> 0.9999,
"the eye left its own view ray"
);
let ratio = |start: f32| {
let mut orbit = OrbitCamera::new(Vec3::ZERO, start, Projection::default());
orbit.zoom(0.25);
orbit.distance() / start
};
assert!(
(ratio(2.0) - ratio(2000.0)).abs() < 1e-5,
"zoom is not scale-free"
);
}
#[test]
fn zoom_stops_short_of_the_pivot_and_short_of_infinity() {
let mut orbit = orbit_camera();
orbit.orbit(0.4, 0.2);
let approach = (orbit.camera().eye - orbit.pivot()).normalize();
for _ in 0..200 {
orbit.zoom(5.0);
}
assert_eq!(
orbit.distance(),
MIN_DISTANCE,
"the near clamp did not hold"
);
let camera = orbit.camera();
let offset = camera.eye - camera.target;
assert!(
offset.dot(approach) > 0.0,
"zooming in passed through the pivot: the eye is at {offset:?} against an approach \
along {approach:?}"
);
assert!(
offset.length() > 0.0 && camera.view().is_finite(),
"the fully zoomed camera has no view matrix"
);
for _ in 0..200 {
orbit.zoom(-5.0);
}
assert_eq!(orbit.distance(), MAX_DISTANCE, "the far clamp did not hold");
assert!(orbit.camera().eye.is_finite());
}
#[test]
fn framing_fits_a_wide_object_in_a_narrow_window_where_height_alone_would_not() {
let bounds = Aabb {
min: Vec3::new(-5.0, -0.5, -0.5),
max: Vec3::new(5.0, 0.5, 0.5),
};
let corners = |bounds: Aabb| {
let (lo, hi) = (bounds.min, bounds.max);
[
Vec3::new(lo.x, lo.y, lo.z),
Vec3::new(hi.x, lo.y, lo.z),
Vec3::new(lo.x, hi.y, lo.z),
Vec3::new(hi.x, hi.y, lo.z),
Vec3::new(lo.x, lo.y, hi.z),
Vec3::new(hi.x, lo.y, hi.z),
Vec3::new(lo.x, hi.y, hi.z),
Vec3::new(hi.x, hi.y, hi.z),
]
};
let extent = |camera: &Camera, aspect: f32, points: &[Vec3]| {
let view_projection = camera.view_projection(aspect);
points.iter().fold(0.0f32, |worst, &point| {
let clip = view_projection * point.extend(1.0);
assert!(clip.w > 0.0, "{point:?} is behind the eye");
worst
.max((clip.x / clip.w).abs())
.max((clip.y / clip.w).abs())
})
};
let mut narrow = 0.0;
for aspect in [2.0f32, 1.0, 0.5] {
let mut orbit = OrbitCamera::new(Vec3::ZERO, 1.0, Projection::default());
orbit.frame(bounds, aspect);
assert_eq!(orbit.pivot(), bounds.center(), "framing did not recentre");
let camera = orbit.camera();
let worst = extent(&camera, aspect, &corners(bounds));
assert!(
worst <= 1.0,
"at aspect {aspect} a corner projected to {worst}, outside the frame"
);
let radius = bounds.half_extent().length();
let (right, up) = orbit.basis();
let silhouette = [
camera.target + right * radius,
camera.target - right * radius,
camera.target + up * radius,
camera.target - up * radius,
];
let reach = extent(&camera, aspect, &silhouette);
assert!(
(0.8..=1.0).contains(&reach),
"at aspect {aspect} the framed sphere only reached {reach} of the frame"
);
if aspect == 0.5 {
narrow = orbit.distance();
} else if aspect == 2.0 {
assert!(
orbit.distance() < narrow || narrow == 0.0,
"a narrow window must back further off than a wide one"
);
}
}
let Projection::Perspective { fov_y, .. } = Projection::default() else {
unreachable!("the default projection is perspective")
};
let radius = bounds.half_extent().length();
let height_only = Camera {
eye: Vec3::Z * (radius * FRAME_MARGIN / (0.5 * fov_y).sin()),
..Camera::default()
};
let missed = extent(&height_only, 0.5, &corners(bounds));
assert!(
missed > 1.0,
"the control is only meaningful if a height-only fit genuinely fails here; it kept \
every corner inside the frame at {missed}"
);
}
#[test]
fn framing_moves_the_camera_without_turning_it() {
let mut orbit = orbit_camera();
orbit.orbit(1.4, -0.6);
let before = orbit.camera();
let facing = (before.eye - before.target).normalize();
orbit.frame(
Aabb {
min: Vec3::new(8.0, 8.0, 8.0),
max: Vec3::new(12.0, 10.0, 12.0),
},
ASPECT,
);
let after = orbit.camera();
assert!(
(after.eye - after.target).normalize().dot(facing) > 0.9999,
"framing turned the camera from {facing:?} to {:?}",
(after.eye - after.target).normalize()
);
assert_eq!(after.target, Vec3::new(10.0, 9.0, 10.0));
}
#[test]
fn framing_a_single_point_leaves_a_usable_camera() {
let point = Vec3::new(3.0, -1.0, 2.0);
let mut orbit = orbit_camera();
orbit.frame(
Aabb {
min: point,
max: point,
},
ASPECT,
);
assert!(
orbit.distance() >= MIN_DISTANCE,
"framing a point put the eye {} m from it",
orbit.distance()
);
let camera = orbit.camera();
assert!(camera.view().is_finite());
let Projection::Perspective { near, .. } = camera.projection else {
unreachable!("an orbit camera is perspective-only")
};
assert!(
orbit.distance() >= near,
"framing a point put the eye {} m from it, inside its own {near} m near plane",
orbit.distance()
);
let depth = camera
.depth_of(point, ASPECT)
.expect("the framed point is in front of the eye");
assert!(
depth > 0.0 && depth <= crcbl_hal::depth::NEAR + 1e-5,
"the framed point projected to depth {depth}, and anything above {} is nearer than \
the near plane and never drawn",
crcbl_hal::depth::NEAR
);
}
#[test]
#[should_panic(expected = "perspective-only")]
fn an_orthographic_projection_is_refused() {
let _ = OrbitCamera::new(
Vec3::ZERO,
4.0,
Projection::Orthographic {
half_height: 1.0,
near: 0.1,
far: 100.0,
},
);
}
#[test]
#[should_panic(expected = "orbit deltas must be finite")]
fn a_non_finite_orbit_delta_is_refused() {
orbit_camera().orbit(f32::NAN, 0.0);
}
#[test]
#[should_panic(expected = "pan deltas must be finite")]
fn a_non_finite_pan_delta_is_refused() {
orbit_camera().pan(0.0, f32::INFINITY);
}
#[test]
#[should_panic(expected = "zoom delta must be finite")]
fn a_non_finite_zoom_delta_is_refused() {
orbit_camera().zoom(f32::NAN);
}
}