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