Skip to main content

mln_engine/camera/
camera.rs

1use std::time::Duration;
2
3use glam::{DQuat, DVec3};
4use mln_style::geo::LatLng;
5use mln_style::unitbezier::UnitBezier;
6
7use crate::geo::{EdgeInsets, ScreenCoordinate};
8
9/// Various options for describing the viewpoint of a map. All fields are
10/// optional.
11/// A partial command replaces animations of its specified fields. Omitted
12/// fields keep their original animation timing. Flights couple center and
13/// zoom; anchored commands couple center with their specified fields.
14/// Replacing any member of a coupled group stops that group.
15/// Anchor and center points are mutually exclusive, with preference for the
16/// center point when both are set.
17#[derive(Clone, Copy, Debug, Default, PartialEq)]
18pub struct CameraOptions {
19    /// Coordinate at the center of the map.
20    pub center: Option<LatLng>,
21    /// Altitude of the center of the map, in meters above sea level, which
22    /// terrain that clamps the center (the map's `center_clamped_to_ground`)
23    /// decides instead.
24    pub center_altitude: Option<f64>,
25    /// Padding around the interior of the view that affects the frame of
26    /// reference for `center`.
27    pub padding: Option<EdgeInsets>,
28    /// Point of reference for `zoom` and `angle`, assuming an origin at the
29    /// top-left corner of the view: a command keeps the location under it in
30    /// place, over terrain the ground drawn there.
31    pub anchor: Option<ScreenCoordinate>,
32    /// Zero-based zoom level. Constrained to the minimum and maximum zoom
33    /// levels.
34    pub zoom: Option<f64>,
35    /// Bearing, measured in degrees from true north. Wrapped to [0, 360).
36    pub bearing: Option<f64>,
37    /// Pitch toward the horizon measured in degrees, with 0 deg resulting in
38    /// a two-dimensional map.
39    pub pitch: Option<f64>,
40    /// Roll, measured in degrees.
41    pub roll: Option<f64>,
42    /// Field of view, measured in degrees.
43    pub fov: Option<f64>,
44}
45
46/// How a camera fits an area in the map's view.
47#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub struct CameraFitOptions {
49    /// The space to leave between the area and each edge of the padded view.
50    pub margin: EdgeInsets,
51    /// The fitted camera's padding. `None` keeps the padding that the map's
52    /// running camera changes head for, or else the map's padding.
53    pub padding: Option<EdgeInsets>,
54    /// The rotation from north, in degrees. `None` keeps the map's.
55    pub bearing: Option<f64>,
56    /// The tilt toward the horizon, in degrees. `None` keeps the map's.
57    pub pitch: Option<f64>,
58    /// The highest zoom the fit may choose. The map's zoom limits apply
59    /// either way.
60    pub max_zoom: Option<f64>,
61}
62
63/// Various options for describing a transition between viewpoints with
64/// animation. All fields are optional; the default values depend on how
65/// this struct is used.
66#[derive(Clone, Copy, Debug, Default, PartialEq)]
67pub struct AnimationOptions {
68    /// Time to animate to the viewpoint defined herein.
69    pub duration: Option<Duration>,
70    /// Average velocity of a [`CameraUpdateMode::Fly`] transition, measured
71    /// in screenfuls per second, assuming a linear timing curve.
72    pub velocity: Option<f64>,
73    /// Zero-based zoom level at the peak of a [`CameraUpdateMode::Fly`]
74    /// transition's flight path.
75    pub min_zoom: Option<f64>,
76    /// The longest a [`CameraUpdateMode::Fly`] transition may take, as GL
77    /// JS's `maxDuration`: a flight whose duration, set or derived from the
78    /// velocity, exceeds it jumps instead. `None` caps nothing beyond what [`Duration`] holds: a
79    /// derived duration it can't hold jumps too. Other camera commands
80    /// ignore it.
81    pub max_duration: Option<Duration>,
82    /// The easing timing curve of the transition.
83    pub easing: Option<UnitBezier>,
84    /// Caller-chosen identity of the command, which
85    /// `Map::cancel_transitions_with_id` matches. Several commands may share
86    /// one.
87    pub transition_id: Option<u64>,
88}
89
90/// How a camera command ended, as the C API's
91/// `mln_camera_transition_outcome` reports it. A command that ended in more
92/// than one way reports [`Cancelled`](Self::Cancelled) if any of it was
93/// cancelled, otherwise [`Closed`](Self::Closed) if any of it was closed,
94/// and otherwise [`Replaced`](Self::Replaced) if any of it was replaced.
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
96pub enum TransitionOutcome {
97    /// The camera finished the change.
98    #[default]
99    Completed,
100    /// `cancel_transitions` or `cancel_transitions_with_id`, a gesture's
101    /// begin or cancel phase, free camera options, or a resize that moved the
102    /// camera back inside its bounds stopped it. A command that fails before
103    /// it moves the camera also reports this.
104    Cancelled,
105    /// A later command took every field that the command (or a momentum part)
106    /// was still animating, so it stopped. A later command that takes only
107    /// some of them leaves it animating the rest.
108    Replaced,
109    /// The map closed before the change ended.
110    Closed,
111}
112
113/// How fast each part of a camera change moves, in its own unit per second.
114#[derive(Clone, Copy, Debug, Default, PartialEq)]
115pub struct CameraVelocity {
116    /// Logical pixels per second that the map's content moves on screen.
117    pub(crate) pan: ScreenCoordinate,
118    /// Zoom levels per second.
119    pub(crate) zoom: f64,
120    /// Degrees per second.
121    pub(crate) bearing: f64,
122    /// Degrees per second.
123    pub(crate) pitch: f64,
124}
125
126/// How a camera command ended, once every field of it has: completed,
127/// cancelled, replaced by later commands, or closed with the map. Other
128/// commands may still be animating. The C API reports the same outcomes.
129#[derive(Clone, Copy, Debug, Default, PartialEq)]
130pub struct TransitionEnd {
131    pub outcome: TransitionOutcome,
132    /// How fast a momentum still moved when it was cancelled, as of the last
133    /// frame that moved the camera, which the next gesture can add to its own
134    /// release. Zero for every other end.
135    pub velocity: CameraVelocity,
136    /// The generation of the first snapshot of the map that shows where the
137    /// change left the camera, as `mln_runtime`'s map handles report it. 0
138    /// when the map closed first, and from the map itself, which ends a
139    /// change before it counts the change's generation.
140    pub generation: u64,
141}
142
143impl AnimationOptions {
144    #[must_use]
145    pub fn new(d: Duration) -> Self {
146        AnimationOptions { duration: Some(d), ..Default::default() }
147    }
148}
149
150/// Various options for accessing physical properties of the underlying camera
151/// entity. A direct access to these properties allows more flexible and
152/// precise controlling of the camera while also being fully compatible and
153/// interchangeable with `CameraOptions`. All fields are optional.
154#[derive(Clone, Copy, Debug, Default, PartialEq)]
155pub struct FreeCameraOptions {
156    /// Position of the camera in the map's world square, whose unit is the
157    /// width of tile 0/0/0: slightly modified web mercator coordinates on a
158    /// Mercator map, where 1 unit is the width of the projected world instead
159    /// of the "mercator meter", and a registered projection's on a map drawn
160    /// in one. Coordinate [0, 0, 0] is the north-west (top-left) corner and
161    /// [1, 1, 0] is the south-east (bottom-right) corner. Z coordinate is the
162    /// altitude in the same units, at the scale the map draws heights at, and
163    /// must respect minimum and maximum zoom values. Zoom is automatically
164    /// computed from the altitude (z).
165    pub position: Option<DVec3>,
166    /// Orientation of the camera as a unit quaternion. On a map in a
167    /// registered projection, it turns from the north of the projection's
168    /// grid.
169    pub orientation: Option<DQuat>,
170}
171
172/// Where a camera change stands in a gesture, as the C API's
173/// `mln_gesture_phase` defines it. `Begin` and `Update` mark a gesture in
174/// progress, and `End` and `Cancel` end it; a gesture whose end starts
175/// momentum stays in progress until the momentum ends.
176#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
177pub enum GesturePhase {
178    /// The change isn't part of a gesture: a command.
179    #[default]
180    None,
181    /// The gesture starts. This cancels every running camera animation
182    /// before the change applies.
183    Begin,
184    /// The gesture continues. To start a gesture that keeps the running
185    /// animations, start it with this phase instead of `Begin`.
186    Update,
187    /// The gesture's last change, which may carry its momentum.
188    End,
189    /// The platform cancelled the gesture. This also cancels every running
190    /// camera animation after the change applies.
191    Cancel,
192}
193
194/// A change to the camera from where it is now, as a gesture makes it
195/// (the C API's `mln_camera_delta`).
196///
197/// The pan and the anchored change are separate camera commands, because an
198/// explicit center overrides an anchor; the anchored change reads the camera
199/// after the pan. The delta's command ends once both have ended.
200#[derive(Clone, Debug, Default, PartialEq)]
201pub struct CameraDelta {
202    /// Moves the map's content this far on the screen, as a drag does.
203    pub offset: Option<ScreenCoordinate>,
204    /// Multiplies the map's scale: 2 zooms in by one level.
205    pub scale: Option<f64>,
206    /// Degrees to add to the bearing.
207    pub bearing: Option<f64>,
208    /// Degrees to add to the pitch.
209    pub pitch: Option<f64>,
210    /// The screen point that `scale`, `bearing` and `pitch` keep in place,
211    /// and that a drag's `offset` holds: on the globe the location under it
212    /// follows the drag, and over terrain, in a delta of [`GesturePhase::None`], the ground
213    /// drawn under it does, while a flat map moves the same wherever it is
214    /// held. It needs one of them, and it combines with `offset` and one of
215    /// the others only in a delta without a duration.
216    pub anchor: Option<ScreenCoordinate>,
217    /// How the gesture keeps moving after this delta, which only a delta in
218    /// the [`GesturePhase::End`] phase carries. Its parts' snaps apply only
219    /// to the parts the gesture changed. With momentum, `animation` may set
220    /// only its transition id, and the command ends when the momentum does.
221    pub momentum: Option<crate::camera::CameraMomentum>,
222    pub animation: AnimationOptions,
223    pub phase: GesturePhase,
224}
225
226/// How [`CameraUpdate`] moves the camera.
227#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
228pub enum CameraUpdateMode {
229    /// At once; the animation's duration is ignored.
230    #[default]
231    Jump,
232    Ease,
233    Fly,
234}
235
236/// Moves the camera to absolute values, as the C API's
237/// `mln_camera_update` does: the counterpart of [`CameraDelta`] for
238/// commands and gestures that know where the camera should go.
239#[derive(Clone, Debug, Default, PartialEq)]
240pub struct CameraUpdate {
241    pub mode: CameraUpdateMode,
242    pub camera: CameraOptions,
243    pub animation: AnimationOptions,
244    pub phase: GesturePhase,
245}
246
247/// Why a [`CameraDelta`] was rejected.
248#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, thiserror::Error)]
249pub enum CameraError {
250    /// An offset, anchor, bearing or pitch isn't finite.
251    #[error("camera delta offset, anchor, bearing and pitch must be finite")]
252    NotFinite,
253    /// The scale isn't finite and positive.
254    #[error("camera delta scale must be finite and positive")]
255    InvalidScale,
256    /// An anchor needs an offset, scale, bearing or pitch to hold in place.
257    #[error("a camera delta anchor requires scale, bearing, or pitch, or an offset to hold")]
258    AnchorWithoutChange,
259    /// Only a delta in the end phase carries momentum.
260    #[error("only a camera delta in the end phase carries momentum")]
261    MomentumOutsideEnd,
262    /// A delta with momentum sets only its animation's transition id: the
263    /// momentum, not an animation, moves the camera.
264    #[error("a camera delta with momentum sets only the transition ID of its animation")]
265    MomentumWithAnimation,
266    /// An anchor combines with an offset and a scale, bearing or pitch only
267    /// in an immediate delta: an anchored ease couples the center with its
268    /// fields, so it would replace an animated pan.
269    #[error("a camera delta anchor combines with offset only in an immediate delta")]
270    AnimatedAnchoredOffset,
271}
272
273impl CameraDelta {
274    /// Checks the delta. An anchor with only an offset is the point a drag
275    /// holds, which the globe needs.
276    pub fn validate(&self) -> Result<(), CameraError> {
277        let finite_point = |p: Option<ScreenCoordinate>| p.is_none_or(|p| p.x.is_finite() && p.y.is_finite());
278        if !finite_point(self.offset)
279            || !finite_point(self.anchor)
280            || !self.bearing.is_none_or(f64::is_finite)
281            || !self.pitch.is_none_or(f64::is_finite)
282        {
283            return Err(CameraError::NotFinite);
284        }
285        if self.scale.is_some_and(|scale| !scale.is_finite() || scale <= 0.0) {
286            return Err(CameraError::InvalidScale);
287        }
288        let anchored = self.scale.is_some() || self.bearing.is_some() || self.pitch.is_some();
289        if self.anchor.is_some() && !anchored && self.offset.is_none() {
290            return Err(CameraError::AnchorWithoutChange);
291        }
292        if self.momentum.is_some() {
293            if self.phase != GesturePhase::End {
294                return Err(CameraError::MomentumOutsideEnd);
295            }
296            let a = &self.animation;
297            if a.duration.is_some()
298                || a.velocity.is_some()
299                || a.min_zoom.is_some()
300                || a.max_duration.is_some()
301                || a.easing.is_some()
302            {
303                return Err(CameraError::MomentumWithAnimation);
304            }
305        }
306        if self.offset.is_some()
307            && self.anchor.is_some()
308            && anchored
309            && self.animation.duration.is_some_and(|duration| duration > Duration::ZERO)
310        {
311            return Err(CameraError::AnimatedAnchoredOffset);
312        }
313        Ok(())
314    }
315}