use kurbo::Affine;
use kurbo::Point;
use kurbo::Rect;
use kurbo::Size;
use kurbo::Vec2;
pub const MIN_ZOOM: f64 = 0.01;
pub const MAX_ZOOM: f64 = 256.0;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Camera {
pub origin: Point,
pub zoom: f64,
pub min_zoom: f64,
pub max_zoom: f64,
}
impl Default for Camera {
fn default() -> Self {
Self {
origin: Point::ORIGIN,
zoom: 1.0,
min_zoom: MIN_ZOOM,
max_zoom: MAX_ZOOM,
}
}
}
impl Camera {
#[must_use]
pub fn world_to_screen(&self) -> Affine {
Affine::scale(self.zoom) * Affine::translate(-self.origin.to_vec2())
}
#[must_use]
pub fn screen_to_world(&self) -> Affine {
Affine::translate(self.origin.to_vec2()) * Affine::scale(1.0 / self.zoom)
}
#[must_use]
pub fn to_world(&self, screen: Point) -> Point {
self.origin + screen.to_vec2() / self.zoom
}
#[must_use]
pub fn to_screen(&self, world: Point) -> Point {
((world - self.origin) * self.zoom).to_point()
}
#[must_use]
pub fn visible(&self, size: Size) -> Rect {
Rect::from_origin_size(self.origin, size / self.zoom)
}
pub fn pan(&mut self, screen_delta: Vec2) {
self.origin -= screen_delta / self.zoom;
}
pub fn zoom_at(&mut self, anchor: Point, factor: f64) {
let world = self.to_world(anchor);
self.zoom = (self.zoom * factor).clamp(self.min_zoom, self.max_zoom);
self.origin = world - anchor.to_vec2() / self.zoom;
}
pub fn fit(&mut self, target: Rect, size: Size, padding: f64) {
let room = Size::new(
(size.width - 2.0 * padding).max(1.0),
(size.height - 2.0 * padding).max(1.0),
);
let zoom = if target.width() > 0.0 && target.height() > 0.0 {
(room.width / target.width()).min(room.height / target.height())
} else {
self.zoom
};
self.zoom = zoom.clamp(self.min_zoom, self.max_zoom);
let center = target.center();
self.origin = center - (size.to_vec2() / 2.0) / self.zoom;
}
}
const FRICTION_PER_SECOND: f64 = 0.002;
const REST_SPEED: f64 = 8.0;
const SAMPLE_WINDOW: f64 = 0.1;
#[derive(Clone, Debug, Default)]
pub struct Inertia {
samples: Vec<(f64, Point)>,
velocity: Vec2,
}
impl Inertia {
pub fn track(&mut self, time: f64, position: Point) {
self.velocity = Vec2::ZERO;
self.samples.push((time, position));
self.samples
.retain(|(sample, _)| time - sample <= SAMPLE_WINDOW);
}
pub fn release(&mut self) {
self.velocity = match (self.samples.first(), self.samples.last()) {
(Some(&(start, from)), Some(&(end, to))) if end > start => (to - from) / (end - start),
_ => Vec2::ZERO,
};
self.samples.clear();
}
pub fn stop(&mut self) {
self.velocity = Vec2::ZERO;
self.samples.clear();
}
#[must_use]
pub fn is_moving(&self) -> bool {
self.velocity.hypot() >= REST_SPEED
}
pub fn step(&mut self, elapsed: f64) -> Option<Vec2> {
if !self.is_moving() || elapsed <= 0.0 {
self.velocity = Vec2::ZERO;
return None;
}
let rate = FRICTION_PER_SECOND.ln();
let decay = (rate * elapsed).exp();
let delta = self.velocity * ((decay - 1.0) / rate);
self.velocity *= decay;
Some(delta)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Pinch {
distance: f64,
midpoint: Point,
}
impl Pinch {
#[must_use]
pub fn start(a: Point, b: Point) -> Self {
Self {
distance: a.distance(b).max(1.0),
midpoint: a.midpoint(b),
}
}
pub fn update(&mut self, camera: &mut Camera, a: Point, b: Point) {
let distance = a.distance(b).max(1.0);
let midpoint = a.midpoint(b);
camera.pan(midpoint - self.midpoint);
camera.zoom_at(midpoint, distance / self.distance);
self.distance = distance;
self.midpoint = midpoint;
}
}
#[cfg(test)]
mod tests {
use super::*;
const EPSILON: f64 = 1e-9;
const ZOOM_EPSILON: f64 = 1e-12;
fn close(a: Point, b: Point) -> bool {
a.distance(b) < EPSILON
}
#[test]
fn world_and_screen_round_trip() {
const ORIGIN: Point = Point::new(100.0, -50.0);
const WORLD: Point = Point::new(130.0, 10.0);
const SCREEN: Point = Point::new(3.0, 4.0);
let camera = Camera {
origin: ORIGIN,
zoom: 2.5,
..Camera::default()
};
assert!(close(camera.to_world(camera.to_screen(WORLD)), WORLD));
assert!(close(
camera.world_to_screen() * WORLD,
camera.to_screen(WORLD)
));
assert!(close(
camera.screen_to_world() * SCREEN,
camera.to_world(SCREEN)
));
}
#[test]
fn zooming_keeps_the_anchor_still() {
const ANCHOR: Point = Point::new(320.0, 240.0);
let mut camera = Camera::default();
let before = camera.to_world(ANCHOR);
camera.zoom_at(ANCHOR, 3.0);
assert!(close(camera.to_world(ANCHOR), before));
assert!((camera.zoom - 3.0).abs() < ZOOM_EPSILON);
camera.zoom_at(ANCHOR, 1e9);
assert!((camera.zoom - MAX_ZOOM).abs() < ZOOM_EPSILON);
}
#[test]
fn fit_centres_the_target() {
const TARGET: Rect = Rect::new(1000.0, 1000.0, 1200.0, 1100.0);
const VIEWPORT: Size = Size::new(800.0, 600.0);
const PADDING: f64 = 20.0;
const FITTED_ZOOM: f64 = 3.8;
let mut camera = Camera::default();
camera.fit(TARGET, VIEWPORT, PADDING);
let viewport_center = (VIEWPORT.to_vec2() / 2.0).to_point();
assert!(close(camera.to_screen(TARGET.center()), viewport_center));
assert!((camera.zoom - FITTED_ZOOM).abs() < ZOOM_EPSILON);
}
#[test]
fn momentum_decays_independently_of_frame_rate() {
const SAMPLE_GAP: f64 = 0.05;
const FLICK: f64 = 50.0;
const COAST_TIME: f64 = 0.5;
let coast = |frame: f64| {
let mut inertia = Inertia::default();
inertia.track(0.0, Point::ORIGIN);
inertia.track(SAMPLE_GAP, Point::new(FLICK, 0.0));
inertia.release();
let mut travelled = Vec2::ZERO;
let mut time = 0.0;
while time < COAST_TIME {
travelled += inertia.step(frame).unwrap_or_default();
time += frame;
}
travelled.x
};
assert!((coast(1.0 / 60.0) - coast(1.0 / 120.0)).abs() < 1.0);
assert!(coast(1.0 / 60.0) > 100.0);
}
#[test]
fn a_pinch_zooms_about_its_midpoint() {
const MIDPOINT: Point = Point::new(150.0, 100.0);
const SPREAD: Vec2 = Vec2::new(50.0, 0.0);
let mut camera = Camera::default();
let mut pinch = Pinch::start(MIDPOINT - SPREAD, MIDPOINT + SPREAD);
let under = camera.to_world(MIDPOINT);
pinch.update(
&mut camera,
MIDPOINT - SPREAD * 2.0,
MIDPOINT + SPREAD * 2.0,
);
assert!((camera.zoom - 2.0).abs() < ZOOM_EPSILON);
assert!(close(camera.to_world(MIDPOINT), under));
}
}