mln-rs-engine 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! The terrain under the camera. Every rule applies only while the map
//! hands the transform a ground ([`TerrainGround`]):
//!
//! - The eye and its near plane stay above the ground, while anything
//!   moves the camera ([`Transform::keep_clear_of_ground`]) and at rest, as
//!   ground loads or changes under them ([`Transform::follow_terrain`]).
//!   At rest, the camera is the one that was asked for, placed on the
//!   ground as it is known now: a raise lowers again once the ground shows
//!   that the camera asked for clears it, so where the camera comes to stand
//!   doesn't depend on the order the ground loaded in. Ground that is still
//!   loading, undrawn or drawn flat before its DEM, shows nothing, so it
//!   keeps the raise.
//! - A gesture holds the altitude, from its first step to the end of its
//!   momentum, lifted by as much as keeps the eye above the ground, which
//!   lowers again once the ground does. A command that runs while its
//!   fingers are up takes the altitude over, and the gesture holds it from
//!   where the command leaves it.
//! - Under the clamp, the center stands on the ground:
//!   - at rest, on the ground under it, where that is known;
//!   - while commands run and no fingers are down, the altitude eases
//!     toward the ground under where they leave the center, and stands on
//!     it as they end ([`Transform::ease_altitude`]);
//!   - brought to rest off the ground, by a cancel or by the end of a
//!     gesture or of its momentum, the center moves along the view onto the
//!     ground, with the eye where it is, so that the picture stays
//!     ([`Transform::come_to_rest`]).
//!
//! The rules are the same on the globe, where heights stand along each
//! point's vertical above the sea-level sphere: the same heights at the
//! center decide the altitude, and the eye, its near plane and the ground
//! under the line of sight are the globe camera's
//! ([`View::ground_under`]).
//!
//! The terrain moves a camera at rest, as ground loads or changes under it,
//! the clamp turns on or the terrain goes, without camera events: the map's
//! snapshots show those moves. What the terrain does to a
//! command's or a gesture's camera happens within it, before the
//! `CameraDidChange` that ends it.

use std::sync::Arc;

use glam::DVec3;
use mln_style::geo::{LatLng, WrapMode};
use mln_style::time::Instant;

use super::transition::Transition;
use super::{CENTER, Transform, flip_y};
use crate::camera::{CameraOptions, Elevation, TransformState, View};

/// How many times the camera is raised over the ground at once: each raise
/// turns or moves the near plane, which can bring another part of it under
/// the ground. Each leaves a small fraction of the shortfall before it,
/// and the raises stop once the camera is clear.
const MAX_EYE_RAISES: usize = 8;

/// A camera at rest whose eye the terrain raised: the center, zoom and
/// pitch that it had before, and the camera that the raise left, which
/// tells whether anything but the terrain moved it since.
#[derive(Clone, Debug)]
pub(super) struct RaisedAtRest {
    asked: Asked,
    left: CameraOptions,
}

/// Which heights the eye keeps clear of.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Heights {
    /// The surface the frame drew ([`Elevation::surface_at`]), which a
    /// moving camera stays above.
    Drawn,
    /// The finest DEM data loaded ([`Elevation::clearance_at`]), the same
    /// whichever camera drew the frame, which a camera at rest stays above.
    Clearance,
}

/// The center, zoom and pitch of the camera that was asked for.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Asked {
    center: LatLng,
    zoom: f64,
    pitch: f64,
}

impl Asked {
    fn of(view: &View) -> Asked {
        Asked { center: view.center(WrapMode::Unwrapped), zoom: view.zoom(), pitch: view.pitch() }
    }

    /// Puts `state`'s center, zoom and pitch back to these.
    fn restore(self, state: &mut TransformState) {
        state.set_pitch(self.pitch);
        state.set_lat_lng_zoom(&self.center, self.zoom);
    }
}

/// The terrain the camera stands on, which the map hands the transform
/// while its style's terrain draws outside tile mode, on every projection.
#[derive(Clone, Debug)]
pub(crate) struct TerrainGround {
    /// The ground the renderer last drew, or `None` before it drew any:
    /// the eye then stays above sea level, and the ground under the center
    /// counts as loading.
    pub(crate) elevation: Option<Arc<dyn Elevation>>,
    /// Whether the center stands on the ground at rest.
    pub(crate) clamped: bool,
}

impl Transform {
    /// Sets the terrain the camera stands on, or `None` without terrain,
    /// which turns off every rule of the camera over terrain. Once the
    /// terrain goes, the view fits the flat map again, a clamped center
    /// goes to sea level, keeping its location and zoom, a camera at rest
    /// whose eye only the terrain raised takes the zoom and pitch it was
    /// asked for again, and a gesture holds the altitude from where that
    /// leaves it.
    pub(crate) fn set_terrain(&mut self, terrain: Option<TerrainGround>) {
        let clamped = self.clamped();
        let goes = self.terrain.is_some() && terrain.is_none();
        self.terrain = terrain;
        if goes {
            self.gesture.altitude = None;
            // Without terrain, the camera that was asked for is clear.
            let found = self.state.camera_options(None);
            if let Some(raised) = self.raised_at_rest.take().filter(|raised| raised.left == found) {
                raised.asked.restore(&mut self.state);
            }
            self.leave_ground();
            // Also before any ground was drawn, as the ground would have
            // overruled the altitude of a clamped center.
            if clamped {
                self.go_to_sea_level();
            }
        }
    }

    /// Fits the view's near and far planes to the flat map again, and
    /// returns whether they fit the ground before.
    fn leave_ground(&mut self) -> bool {
        let fit = self.view().terrain_min_elevation().is_some();
        if fit {
            self.state.set_terrain_min_elevation(None);
        }
        fit
    }

    /// Puts the center at sea level, keeping its location and zoom.
    fn go_to_sea_level(&mut self) {
        if self.view().center_altitude() != 0.0 {
            self.state.set_center_altitude(0.0);
        }
    }

    /// Fits the view's near and far planes to the lowest ground that
    /// `elevation` has in the tile under the center, or to sea level where it
    /// has none.
    fn fit_planes(&mut self, elevation: &dyn Elevation) {
        let min_elevation = Some(lowest_ground(self.view(), elevation));
        if min_elevation != self.view().terrain_min_elevation() {
            self.state.set_terrain_min_elevation(min_elevation);
        }
    }

    /// Moves the camera onto the terrain's ground. While there is ground,
    /// the view's near and far planes fit the lowest ground of the tile
    /// under the center, and a camera at rest whose center is clamped
    /// stands on the ground there, unless it is still loading. Where that
    /// leaves the eye, or its near plane over drawn ground, below the
    /// ground, as when ground loads under a camera that a jump placed
    /// before it drew, the eye rises by pitch and zoom as a command's does
    /// ([`Self::raise_clear_of_ground`]), from the zoom and pitch that it had
    /// before the terrain raised it, while nothing else moved it since and
    /// the ground under that camera's eye and near plane is known
    /// ([`Self::place_at_rest`]). A camera that a command moves
    /// takes the altitude its frames give it, which ease onto the ground,
    /// and a gesture that holds the altitude lifts it just over the ground
    /// as it is now, eye and near plane. Once there is no ground, the
    /// planes fit the flat map again, and a clamped center goes back to sea
    /// level, once.
    ///
    /// The terrain moves the camera, not a command, so this reports no
    /// camera change. Returns whether the view changed.
    pub(crate) fn follow_terrain(&mut self) -> bool {
        let Some(TerrainGround { elevation, clamped }) = &self.terrain else { return false };
        let (elevation, clamped) = (elevation.clone(), *clamped);
        let before = self.view().params().clone();
        // The camera as the terrain last left it, before this moves it.
        let found = self.state.camera_options(None);
        match &elevation {
            Some(elevation) => self.fit_planes(&**elevation),
            // Once, as the planes fit the flat map from then on.
            None => {
                if self.leave_ground() && clamped {
                    self.go_to_sea_level();
                }
            }
        }
        // A command of the pitch alone doesn't count as moving the camera,
        // but its frames set the altitude too.
        let at_rest = !self.is_camera_moving() && !self.in_transition();
        if self.gesture_holds_altitude() {
            self.lift(elevation.as_deref());
        } else if at_rest {
            self.place_at_rest(&found, elevation.as_deref(), clamped);
        }
        *self.view().params() != before
    }

    /// Places a camera at rest, which this follow `found`, on `elevation`:
    /// the camera that was asked for, with a clamped center on the ground
    /// and the eye raised clear of it. The camera asked for is the one
    /// before the terrain last raised the eye, while nothing else moved the
    /// camera since, and else the camera as it is. The eye clears the
    /// finest DEM data loaded ([`Heights::Clearance`]), which the raised
    /// camera's own coarser tiles don't change. A raised camera takes the
    /// camera asked for again where that data is loaded under its eye and
    /// near plane, which shows whether it clears the ground; where some of
    /// it is still loading, it keeps the raise it has.
    fn place_at_rest(&mut self, found: &CameraOptions, elevation: Option<&dyn Elevation>, clamped: bool) {
        let raised = self.raised_at_rest.take().filter(|raised| raised.left == *found);
        let asked = raised.as_ref().map_or_else(|| Asked::of(self.view()), |raised| raised.asked);
        let mut trial = self.state.clone();
        if raised.is_some() {
            asked.restore(&mut trial);
            if let Some(altitude) = elevation
                .filter(|_| clamped)
                .and_then(|ground| ground.ground_at(trial.view().center(WrapMode::Wrapped)))
            {
                trial.set_center_altitude(altitude);
            }
        }
        if raised.is_some() && clearance_known_under(trial.view(), elevation) {
            self.state = trial;
        }
        if clamped {
            self.stand_on_ground();
        }
        // A raise that the limits hold back can move the center, which then
        // stands on the ground where it is, and clears it from there, until
        // a raise leaves it where it stands.
        for _ in 0..MAX_EYE_RAISES {
            self.raise_clear_of_ground(elevation, Heights::Clearance);
            if !(clamped && self.stand_on_ground()) {
                break;
            }
        }
        let view = self.view();
        if (view.zoom(), view.pitch()) != (asked.zoom, asked.pitch) {
            let left = self.state.camera_options(None);
            self.raised_at_rest = Some(RaisedAtRest { asked, left });
        }
    }

    /// Whether there is terrain and it clamps the center.
    pub(super) fn clamped(&self) -> bool {
        self.terrain.as_ref().is_some_and(|terrain| terrain.clamped)
    }

    /// Whether a gesture holds the altitude: from its first step to the end
    /// of its momentum, except while its fingers are up and a command runs.
    fn gesture_holds_altitude(&self) -> bool {
        self.gesture_in_progress && (self.gesture.active || !self.transitions.iter().any(Transition::is_command))
    }

    /// Puts the center at the height of the ground under it, where that is
    /// known, and returns whether that moved it.
    pub(super) fn stand_on_ground(&mut self) -> bool {
        let Some(TerrainGround { elevation: Some(ground), .. }) = &self.terrain else { return false };
        let view = self.view();
        let altitude = ground.ground_at(view.center(WrapMode::Wrapped)).filter(|&h| h != view.center_altitude());
        if let Some(altitude) = altitude {
            self.state.set_center_altitude(altitude);
        }
        altitude.is_some()
    }

    /// Sets the altitude of `camera`, a frame's camera at `now` composed of
    /// the running commands, over terrain that clamps the center: from the
    /// altitude the camera has, toward the ground under where the commands
    /// leave the center, by this frame's share of what is left of the way of
    /// the command that ends last, so that it arrives as they end. Where
    /// they leave the center is where the command that owns it ends it, or
    /// else where it is. Ground that lands, or a command that starts, ends
    /// or hands the center over, turns the next frame toward the new target
    /// from where the altitude is. While that ground is unknown, as at the
    /// end of a flight past the ground the renderer drew, or a gesture holds
    /// the altitude, it stays where it is.
    ///
    /// Returns whether this frame ends the commands, which then stand the
    /// center on the ground under where they put it
    /// ([`Self::stand_on_ground`]).
    pub(super) fn ease_altitude(&mut self, camera: &mut CameraOptions, now: Option<Instant>) -> bool {
        let before = std::mem::replace(&mut self.last_frame, now);
        let Some(TerrainGround { elevation: Some(ground), clamped: true }) = &self.terrain else { return false };
        if self.gesture_holds_altitude() {
            return false;
        }
        let commands = || self.transitions.iter().filter(|transition| transition.is_command());
        let Some(pacing) = commands().max_by_key(|transition| transition.remaining(now)) else { return false };
        let end = match commands().find(|transition| transition.fields & CENTER != 0) {
            Some(owner) => owner.end_center(&self.state, camera, &**ground),
            None => self.view().center(WrapMode::Wrapped),
        };
        let Some(target) = ground.ground_at(end) else { return false };
        let altitude = self.view().center_altitude();
        // An easing that overshoots its end, or backs up past its start,
        // takes the altitude no farther than the target: it arrives where
        // the share first reaches 1, and holds while the share falls back.
        let share = pacing.share(now).clamp(0.0, 1.0);
        let reached = before.map_or(0.0, |before| pacing.share(Some(before)).clamp(0.0, 1.0)).min(share);
        let lands = pacing.remaining(now).is_zero();
        camera.center_altitude = Some(if lands || reached == 1.0 {
            target
        } else {
            altitude + (target - altitude) * (share - reached) / (1.0 - reached)
        });
        lands
    }

    /// Stands a camera that a command, a gesture or a momentum brought to
    /// rest over terrain that clamps the center on the ground, once no
    /// gesture or command moves it. A center off the drawn ground under it,
    /// as a cancel or a gesture leaves it, moves along the view onto the
    /// ground its line of sight meets, with the eye where it is
    /// ([`TransformState::recenter_on`]); what
    /// that leaves off the ground, or all of it where the view meets no
    /// drawn ground or the limits refuse the move, the center takes up in
    /// altitude. The caller reports the change. Returns whether the camera
    /// moved.
    ///
    /// [`TransformState::recenter_on`]: crate::camera::TransformState::recenter_on
    pub(super) fn come_to_rest(&mut self) -> bool {
        let Some(TerrainGround { elevation: Some(ground), clamped: true }) = &self.terrain else { return false };
        let view = self.view();
        let off = ground.ground_at(view.center(WrapMode::Wrapped)).is_some_and(|h| h != view.center_altitude());
        if !off || self.gesture_in_progress || !self.transitions.is_empty() {
            return false;
        }
        let ground = Arc::clone(ground);
        let center = flip_y(view, &view.padding().center_in(view.size()));
        if let Some(hit) = view.ground_under(&center, &*ground) {
            // A refused move leaves the state as it is.
            let _ = self.state.recenter_on(&hit);
        }
        self.stand_on_ground();
        true
    }

    /// Keeps the eye of a moving camera out of the terrain: the view's near
    /// and far planes fit the ground under the center, as at rest, and
    /// where the eye, or the near plane over drawn ground, would be below
    /// the ground, a gesture that holds the altitude lifts it
    /// ([`Self::lift`]), and anything else raises the eye by pitch and zoom,
    /// keeping its place and the center it looks at. Before the renderer drew
    /// any ground, the eye stays above sea level. Without terrain it does
    /// nothing.
    pub(super) fn keep_clear_of_ground(&mut self) {
        let Some(terrain) = &self.terrain else { return };
        let elevation = terrain.elevation.clone();
        // The frame's center may have moved since the planes last fit it.
        if let Some(elevation) = &elevation {
            self.fit_planes(&**elevation);
        }
        if self.gesture_holds_altitude() {
            self.lift(elevation.as_deref());
            return;
        }
        // The gesture holds the altitude again from where this leaves it.
        self.gesture.altitude = None;
        self.raise_clear_of_ground(elevation.as_deref(), Heights::Drawn);
    }

    /// Where the eye, or the near plane over drawn ground, is below the
    /// ground's `heights`, raises the eye by pitch and zoom, keeping its
    /// place and the center it looks at, up to [`MAX_EYE_RAISES`] times.
    /// Without `elevation`, the eye stays above sea level.
    ///
    /// Ground less than a thousandth of a pixel at the zoom above them
    /// counts as clear, out of sight: the raises only approach the ground,
    /// and a camera at rest that this raised again would creep after every
    /// command.
    fn raise_clear_of_ground(&mut self, elevation: Option<&dyn Elevation>, heights: Heights) {
        for _ in 0..MAX_EYE_RAISES {
            let view = self.view();
            let shortfall = eye_shortfall(view, elevation, heights);
            if !(shortfall > view.meters_per_pixel() / 1000.0 && self.state.raise_eye(shortfall)) {
                return;
            }
        }
    }

    /// Puts the center at the altitude the gesture holds, raised by as far
    /// as the ground reaches above the eye or the near plane there, so that
    /// the lift lowers again once the ground under them does. The gesture
    /// holds the altitude the camera has when it first lifts it. On Mercator
    /// a raise moves the eye and the near plane straight up over the same
    /// ground, so one clears them; on the globe it takes up to as many as a
    /// command's.
    fn lift(&mut self, elevation: Option<&dyn Elevation>) {
        let mut altitude = *self.gesture.altitude.get_or_insert(self.view().center_altitude());
        for raise in 0..=MAX_EYE_RAISES {
            if self.view().center_altitude() != altitude {
                self.state.set_center_altitude(altitude);
            }
            let shortfall = eye_shortfall(self.view(), elevation, Heights::Drawn);
            if !(shortfall > 0.0 && raise < MAX_EYE_RAISES) {
                return;
            }
            altitude += shortfall;
        }
    }
}

/// The lowest ground that `elevation` has in the tile under the center of
/// `view`, or sea level where it has none, in meters: what the view's near
/// and far planes fit while terrain draws.
pub(crate) fn lowest_ground(view: &View, elevation: &dyn Elevation) -> f64 {
    elevation.min_at(view.center(WrapMode::Wrapped)).unwrap_or(0.0)
}

/// Whether `elevation` has the clearance under the eye of `view` and under
/// each point of its near plane ([`Elevation::clearance_at`]), which shows
/// whether that camera clears the ground: whether DEM data has loaded under
/// all of them. Also where no ground draws (`elevation` is `None`), as the
/// eye then only has to clear sea level. Ground that a DEM source has no
/// data for has none for good, and keeps a raise over it.
fn clearance_known_under(view: &View, elevation: Option<&dyn Elevation>) -> bool {
    let Some(elevation) = elevation else { return true };
    let known = |point: DVec3| elevation.clearance_at(point.truncate()).is_some();
    known(view.eye_position()) && view.near_plane_points().into_iter().all(known)
}

/// How far the ground's `heights` reach above the eye of `view`, or above a
/// point of its near plane over ground that has them, in meters, whichever
/// is more; zero or less while all are clear. The ground under the eye is
/// sea level where it has none, or before any was drawn (`elevation` is
/// `None`); then only the eye counts.
fn eye_shortfall(view: &View, elevation: Option<&dyn Elevation>, heights: Heights) -> f64 {
    let eye = view.eye_position();
    let height = |elevation: &dyn Elevation, world: glam::DVec2| match heights {
        Heights::Drawn => elevation.surface_at(world),
        Heights::Clearance => elevation.clearance_at(world),
    };
    let above = |point: DVec3| elevation.and_then(|elevation| height(elevation, point.truncate())).map(|h| h - point.z);
    let mut shortfall = above(eye).unwrap_or(-eye.z);
    if elevation.is_some() {
        for point in view.near_plane_points() {
            shortfall = above(point).map_or(shortfall, |above| shortfall.max(above));
        }
    }
    shortfall
}