mln-rs-engine 0.0.23

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
//! How gestures move each part of the camera, how individual gestures behave,
//! and the recognizer's platform and accessibility metrics.

use std::time::Duration;

use crate::camera::{InvalidMomentum, MomentumDecay, MomentumSnap};

/// Values every `spacing` from `offset`, in the part's unit, that report a
/// [`GestureEvent::Notch`](crate::gestures::GestureEvent::Notch) as a gesture moves the
/// part to or across one, for the host to play as haptic feedback. Bearing
/// notches lie within one turn from the offset.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Notch {
    /// Positive.
    pub spacing: f64,
    pub offset: f64,
    /// The host's name for the feedback, such as which haptic to play, which
    /// the notch's events carry.
    pub kind: u32,
}

impl Notch {
    /// North.
    pub(crate) const NORTH: Notch = Notch { spacing: 360.0, offset: 0.0, kind: 0 };
}

/// The point that a gesture's zoom or rotation holds in place.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum GestureAnchor {
    /// The gesture's focal point: pointer position, pinch midpoint, or press
    /// point.
    #[default]
    FocalPoint,
    /// The camera's center, which the viewport's padding offsets.
    CameraCenter,
}

/// How gestures move the map's content.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PanOptions {
    /// Whether gestures pan: drags, two fingers moving together, and deltas.
    pub enabled: bool,
    /// How a release glides; without it, the pan stops where the gesture
    /// leaves it.
    pub momentum: Option<MomentumDecay>,
}

/// How gestures move the zoom, the bearing or the pitch.
#[derive(Clone, Debug, PartialEq)]
pub struct AxisOptions {
    /// Whether gestures move the part.
    pub enabled: bool,
    /// How a release glides; without it, the part stops where the gesture
    /// leaves it.
    pub momentum: Option<MomentumDecay>,
    /// Where the part settles once its glide ends, after a gesture that
    /// changed it.
    pub snap: Option<MomentumSnap>,
    /// Where the part reports notches while the recognizer's gestures, their
    /// glides and their snaps move it. Several notches at one value report
    /// one event, with the kind of the first in the list.
    pub notches: Vec<Notch>,
}

/// One part of the camera that a gesture moves along a single value.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Axis {
    /// In zoom levels.
    Zoom,
    /// In degrees clockwise from north.
    Bearing,
    /// In degrees from looking straight down.
    Pitch,
}

/// Camera-level rules: what each camera part is allowed to do, and how it
/// glides, settles, and emits haptic notches regardless of which gesture moved
/// it.
#[derive(Clone, Debug, PartialEq)]
pub struct GestureAxes {
    pub pan: PanOptions,
    pub zoom: AxisOptions,
    pub bearing: AxisOptions,
    pub pitch: AxisOptions,
}

impl Default for GestureAxes {
    fn default() -> Self {
        let axis = |momentum: MomentumDecay, snap: Option<MomentumSnap>, notches: Vec<Notch>| AxisOptions {
            enabled: true,
            momentum: Some(momentum),
            snap,
            notches,
        };
        GestureAxes {
            pan: PanOptions { enabled: true, momentum: Some(MomentumDecay::PAN) },
            zoom: axis(MomentumDecay::ZOOM, None, Vec::new()),
            bearing: axis(MomentumDecay::BEARING, Some(MomentumSnap::BEARING), vec![Notch::NORTH]),
            pitch: axis(MomentumDecay::PITCH, None, Vec::new()),
        }
    }
}

/// How single-pointer drags move the camera.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DragOptions {
    /// Whether single-pointer pan drags pan the map.
    pub pan: bool,
    /// Degrees of bearing per logical pixel of rightward rotate drag; negative
    /// reverses.
    pub rotate_bearing_per_px: f64,
    /// Degrees of pitch per logical pixel of downward rotate drag; negative
    /// tilts up as the pointer drags up.
    pub rotate_pitch_per_px: f64,
    /// The point held fixed while a rotate drag turns or tilts the map.
    pub rotate_anchor: GestureAnchor,
}

impl Default for DragOptions {
    fn default() -> Self {
        DragOptions {
            pan: true,
            rotate_bearing_per_px: 0.5,
            rotate_pitch_per_px: -0.5,
            rotate_anchor: GestureAnchor::CameraCenter,
        }
    }
}

/// How two-pointer pinch, twist, and tilt gestures move the camera.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PinchOptions {
    /// Whether two fingers moving together pan the map.
    pub pan: bool,
    /// Whether spreading or closing two fingers zooms the map.
    pub zoom: bool,
    /// Whether twisting two fingers rotates the map.
    pub rotate: bool,
    /// Whether dragging two fingers vertically tilts the map.
    pub pitch: bool,
    /// When false, a pinch does not rotate once it starts zooming.
    pub rotate_during_zoom: bool,
    /// The point held fixed while a pinch zooms.
    pub zoom_anchor: GestureAnchor,
    /// The point held fixed while a pinch rotates.
    pub rotate_anchor: GestureAnchor,
    /// Degrees of pitch per logical pixel of downward two-finger drag;
    /// negative tilts up as fingers move up.
    pub pitch_per_px: f64,
}

impl Default for PinchOptions {
    fn default() -> Self {
        PinchOptions {
            pan: true,
            zoom: true,
            rotate: true,
            pitch: true,
            rotate_during_zoom: true,
            zoom_anchor: GestureAnchor::FocalPoint,
            rotate_anchor: GestureAnchor::FocalPoint,
            pitch_per_px: -0.5,
        }
    }
}

/// How a double-tap drag (quick zoom) zooms the camera.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TapDragOptions {
    /// Whether a held second press after a tap zooms on drag instead of
    /// panning.
    pub enabled: bool,
    /// Zoom levels per logical pixel downward; negative zooms in as the
    /// pointer moves up.
    pub zoom_per_px: f64,
    /// The point held fixed while zooming.
    pub anchor: GestureAnchor,
}

impl Default for TapDragOptions {
    fn default() -> Self {
        TapDragOptions { enabled: true, zoom_per_px: 1.0 / 128.0, anchor: GestureAnchor::CameraCenter }
    }
}

/// How a double tap or two-finger tap zooms the camera.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TapZoomOptions {
    /// Whether the tap zooms the camera. When false, the tap still reports its
    /// [`GestureEvent`](crate::gestures::GestureEvent) for the host to handle.
    pub enabled: bool,
    /// Zoom levels added on tap; negative zooms out.
    pub zoom_levels: f64,
    /// The point held fixed while zooming.
    pub anchor: GestureAnchor,
}

impl TapZoomOptions {
    /// Default double-tap zoom: one level in around the tap.
    pub const DOUBLE_TAP: Self = Self { enabled: true, zoom_levels: 1.0, anchor: GestureAnchor::FocalPoint };
    /// Default two-finger-tap zoom: one level out around the fingers' middle.
    pub const TWO_FINGER_TAP: Self = Self { enabled: true, zoom_levels: -1.0, anchor: GestureAnchor::FocalPoint };
}

/// How a box-zoom drag zooms the camera.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BoxZoomOptions {
    /// Whether box-zoom drags draw a box and zoom to it on release.
    pub enabled: bool,
    /// How long the ease into the boxed bounds lasts; zero jumps immediately.
    pub duration: Duration,
}

impl Default for BoxZoomOptions {
    fn default() -> Self {
        BoxZoomOptions { enabled: true, duration: Duration::from_millis(500) }
    }
}

/// How discrete and continuous deltas (wheel, trackpad, keys, rotary, tap
/// zooms) step and end.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DeltaOptions {
    /// How long a discrete delta eases; zero applies the full delta immediately
    /// within the zoom range without stepping across frames.
    pub step_duration: Duration,
    /// Maximum zoom levels applied in one step for continuous deltas and eased
    /// discrete steps; eased discrete deltas carry the rest to later frames.
    /// Does not cap immediate discrete deltas when `step_duration` is zero.
    /// Finite and at least `1e-6`.
    pub max_step_zoom: f64,
    /// Deltas remain one gesture until this long after their last input and
    /// ease.
    pub idle: Duration,
}

impl Default for DeltaOptions {
    fn default() -> Self {
        DeltaOptions { step_duration: Duration::from_millis(200), max_step_zoom: 1.0, idle: Duration::from_millis(200) }
    }
}

/// Per-gesture recognition and mapping rules.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GestureBehavior {
    pub drag: DragOptions,
    pub pinch: PinchOptions,
    pub tap_drag: TapDragOptions,
    pub double_tap: TapZoomOptions,
    pub two_finger_tap: TapZoomOptions,
    pub box_zoom: BoxZoomOptions,
    pub deltas: DeltaOptions,
}

impl Default for GestureBehavior {
    fn default() -> Self {
        GestureBehavior {
            drag: DragOptions::default(),
            pinch: PinchOptions::default(),
            tap_drag: TapDragOptions::default(),
            double_tap: TapZoomOptions::DOUBLE_TAP,
            two_finger_tap: TapZoomOptions::TWO_FINGER_TAP,
            box_zoom: BoxZoomOptions::default(),
            deltas: DeltaOptions::default(),
        }
    }
}

/// Platform and accessibility metrics: slops, timeouts, and multi-touch
/// recognition thresholds. Distances are in logical pixels.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GestureMetrics {
    /// How far a touch press may move and still be a tap; drags start past it.
    pub touch_slop: f64,
    /// How far a mouse or pen press may move and still be a tap; drags start
    /// past it.
    pub pointer_slop: f64,
    /// Maximum distance between the two taps of a double tap, and maximum
    /// travel of a two-finger tap's fingers.
    pub double_tap_slop: f64,
    /// Maximum time between the two taps of a double tap, and between the two
    /// fingers of a two-finger tap.
    pub double_tap_interval: Duration,
    /// How long a press stays still to become a long press (positive).
    pub long_press: Duration,
    /// Zoom levels a pinch spreads or closes before it starts zooming.
    pub pinch_zoom_threshold: f64,
    /// Logical pixels along the fingers' circle a twist travels before it
    /// starts rotating.
    pub pinch_rotate_threshold: f64,
    /// Logical pixels both fingers must move before two-finger tilt vs pinch
    /// is decided.
    pub pinch_pitch_slop: f64,
}

impl Default for GestureMetrics {
    fn default() -> Self {
        GestureMetrics {
            touch_slop: 8.0,
            pointer_slop: 3.0,
            double_tap_slop: 40.0,
            double_tap_interval: Duration::from_millis(300),
            long_press: Duration::from_millis(500),
            pinch_zoom_threshold: 0.1,
            pinch_rotate_threshold: 25.0,
            pinch_pitch_slop: 2.0,
        }
    }
}

/// Why [`GestureOptions`] are out of range.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum InvalidGestureOptions {
    #[error("the momentum of {0}: {1}")]
    Momentum(&'static str, InvalidMomentum),
    #[error("the snap of {0}: {1}")]
    Snap(&'static str, InvalidMomentum),
    #[error("a notch of {0} needs a positive spacing and a finite offset")]
    Notch(&'static str),
    #[error("gesture rates and tap zoom levels must be finite")]
    Rate,
    #[error("deltas.max_step_zoom must be finite and at least 1e-6")]
    MaxStepZoom,
    #[error("gesture metric {0} must be finite and not negative")]
    Metric(&'static str),
    #[error("long_press must be positive")]
    LongPress,
}

/// How the recognizer moves each part of the camera, interprets gestures, and
/// applies platform slops and timeouts.
#[derive(Clone, Debug, PartialEq)]
pub struct GestureOptions {
    pub axes: GestureAxes,
    pub gestures: GestureBehavior,
    pub metrics: GestureMetrics,

    /// Whether a release that catches the recognizer's last glide (a flick
    /// that interrupts a glide going its way) adds that glide's speed, as
    /// `UIScrollView`, Android's scroll flywheel and Compose do. Each part's
    /// decay still caps the speed.
    pub(crate) carry_caught_glide: bool,
    /// Whether a press stops every camera animation, so that the map holds
    /// still under it, or only the recognizer's own.
    pub(crate) interrupt_animations: bool,
    /// The [`AnimationOptions::transition_id`](crate::camera::AnimationOptions::transition_id)
    /// of the eases and momentum the recognizer starts.
    pub(crate) transition_id: u64,
}

impl GestureOptions {
    /// The options of `axis`.
    #[must_use]
    pub(crate) fn axis(&self, axis: Axis) -> &AxisOptions {
        match axis {
            Axis::Zoom => &self.axes.zoom,
            Axis::Bearing => &self.axes.bearing,
            Axis::Pitch => &self.axes.pitch,
        }
    }

    /// Checks every axis's momentum, snap and notches, every gesture rate, and
    /// every platform metric.
    pub fn validate(&self) -> Result<(), InvalidGestureOptions> {
        let momentum = |name, momentum: Option<MomentumDecay>| {
            momentum
                .map_or(Ok(()), |decay| decay.validate().map_err(|error| InvalidGestureOptions::Momentum(name, error)))
        };
        momentum("pan", self.axes.pan.momentum)?;
        for (name, part) in [("zoom", &self.axes.zoom), ("bearing", &self.axes.bearing), ("pitch", &self.axes.pitch)] {
            momentum(name, part.momentum)?;
            if let Some(snap) = part.snap {
                snap.validate().map_err(|error| InvalidGestureOptions::Snap(name, error))?;
            }
            let valid = |notch: &Notch| notch.spacing.is_finite() && notch.spacing > 0.0 && notch.offset.is_finite();
            if !part.notches.iter().all(valid) {
                return Err(InvalidGestureOptions::Notch(name));
            }
        }
        let rates = [
            self.gestures.drag.rotate_bearing_per_px,
            self.gestures.drag.rotate_pitch_per_px,
            self.gestures.pinch.pitch_per_px,
            self.gestures.tap_drag.zoom_per_px,
            self.gestures.double_tap.zoom_levels,
            self.gestures.two_finger_tap.zoom_levels,
        ];
        if !rates.iter().all(|value| value.is_finite()) {
            return Err(InvalidGestureOptions::Rate);
        }
        if !self.gestures.deltas.max_step_zoom.is_finite() || self.gestures.deltas.max_step_zoom < 1e-6 {
            return Err(InvalidGestureOptions::MaxStepZoom);
        }
        for (name, value) in [
            ("touch_slop", self.metrics.touch_slop),
            ("pointer_slop", self.metrics.pointer_slop),
            ("double_tap_slop", self.metrics.double_tap_slop),
            ("pinch_zoom_threshold", self.metrics.pinch_zoom_threshold),
            ("pinch_rotate_threshold", self.metrics.pinch_rotate_threshold),
            ("pinch_pitch_slop", self.metrics.pinch_pitch_slop),
        ] {
            if !value.is_finite() || value < 0.0 {
                return Err(InvalidGestureOptions::Metric(name));
            }
        }
        if self.metrics.long_press.is_zero() {
            return Err(InvalidGestureOptions::LongPress);
        }
        Ok(())
    }
}

impl Default for GestureOptions {
    fn default() -> Self {
        GestureOptions {
            axes: GestureAxes::default(),
            gestures: GestureBehavior::default(),
            metrics: GestureMetrics::default(),
            carry_caught_glide: true,
            interrupt_animations: true,
            // "gestures" in ASCII.
            transition_id: 0x6765_7374_7572_6573,
        }
    }
}