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