rustial-engine 0.0.1

Framework-agnostic 2.5D map engine for rustial
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Input event protocol for the map engine.
//!
//! [`InputEvent`] is the **sole** channel through which external input
//! reaches the engine camera.  It is consumed by:
//!
//! - [`CameraController::handle_event`](crate::CameraController) --
//!   dispatches to `pan`, `zoom`, `rotate`, or viewport resize.
//! - [`MapState::handle_input`](crate::MapState) -- convenience
//!   forwarding wrapper used by host applications.
//! - The Bevy renderer (`map_input::handle_default_input`) -- translates
//!   mouse / keyboard Bevy events into `InputEvent` values.
//! - Pure WGPU host applications -- translate winit events manually.
//!
//! # Design
//!
//! - **Framework-agnostic**: no dependency on winit, Bevy, or any
//!   windowing crate.  The host is responsible for producing events.
//! - **Value semantics**: `Copy + Clone + PartialEq + Debug` -- cheap
//!   to pass, compare, and log.
//! - **Units are documented per variant**: pixels for spatial deltas,
//!   radians for rotation, multiplicative factor for zoom.
//! - Convenience constructors (`pan`, `zoom_in`, `zoom_out`, `rotate`,
//!   `resize`) are provided so callers do not need to write the struct
//!   literal syntax.

use std::fmt;

// ---------------------------------------------------------------------------
// Touch types
// ---------------------------------------------------------------------------

/// Phase of a touch contact's lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TouchPhase {
    /// A new finger has made contact with the screen.
    Started,
    /// An existing touch has moved.
    Moved,
    /// The finger has lifted from the screen.
    Ended,
    /// The OS cancelled the touch (e.g. palm rejection).
    Cancelled,
}

/// A single touch contact point.
///
/// The `id` field uniquely identifies a finger across its lifecycle
/// (started → moved → ended).  Coordinates are in **logical pixels**.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TouchContact {
    /// Unique identifier for this finger (stable across phases).
    pub id: u64,
    /// Phase of the touch event.
    pub phase: TouchPhase,
    /// X position in logical pixels.
    pub x: f64,
    /// Y position in logical pixels.
    pub y: f64,
}

// ---------------------------------------------------------------------------
// InputEvent
// ---------------------------------------------------------------------------

/// An input event that can be dispatched to the engine.
///
/// All spatial values are in **logical pixels** unless otherwise noted.
/// Rotation values are in **radians**.
///
/// # Examples
///
/// ```
/// use rustial_engine::InputEvent;
///
/// // Drag the map 10 px right and 5 px down.
/// let pan = InputEvent::pan(10.0, 5.0);
///
/// // Zoom in by 10 %.
/// let zoom = InputEvent::zoom_in(1.1);
///
/// // Tilt the camera 5 degrees (? 0.087 rad).
/// let rotate = InputEvent::rotate(0.0, 0.087);
///
/// // Viewport resized.
/// let resize = InputEvent::resize(1920, 1080);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum InputEvent {
    /// Pan the camera by a screen-space delta.
    ///
    /// Positive `dx` moves the viewport to the **right** (map moves left).
    /// Positive `dy` moves the viewport **down** (map moves up).
    Pan {
        /// Horizontal pixel delta (positive = right).
        dx: f64,
        /// Vertical pixel delta (positive = down).
        dy: f64,
        /// Cursor's X position in logical pixels (where the drag started or currently is).
        x: Option<f64>,
        /// Cursor's Y position in logical pixels.
        y: Option<f64>,
    },

    /// Zoom by a multiplicative factor.
    ///
    /// - `factor > 1.0` zooms **in** (closer to the ground).
    /// - `0 < factor < 1.0` zooms **out**.
    /// - `factor <= 0`, `NaN`, or `+/-Inf` are silently ignored by the
    ///   [`CameraController`](crate::CameraController).
    Zoom {
        /// Multiplicative zoom factor.
        factor: f64,
        /// Cursor X position in logical pixels used as the zoom anchor.
        x: Option<f64>,
        /// Cursor Y position in logical pixels used as the zoom anchor.
        y: Option<f64>,
    },

    /// Rotate the camera by delta yaw and delta pitch.
    ///
    /// - `delta_yaw` rotates the bearing (positive = clockwise when
    ///   viewed from above).
    /// - `delta_pitch` tilts the camera (positive = toward horizon).
    Rotate {
        /// Change in yaw (bearing) in radians.
        delta_yaw: f64,
        /// Change in pitch (tilt) in radians.
        delta_pitch: f64,
    },

    /// Notify the engine of a viewport resize.
    ///
    /// The engine uses logical pixel dimensions (not physical) so that
    /// zoom-level calculations match the standard slippy-map convention.
    Resize {
        /// New viewport width in logical pixels.
        width: u32,
        /// New viewport height in logical pixels.
        height: u32,
    },

    /// A raw touch contact event.
    ///
    /// The host application emits one `Touch` per finger per phase
    /// change.  The engine's [`GestureRecognizer`](crate::gesture::GestureRecognizer)
    /// accumulates these into high-level `Pan` / `Zoom` / `Rotate`
    /// events.
    Touch(TouchContact),
}

// ---------------------------------------------------------------------------
// Convenience constructors
// ---------------------------------------------------------------------------

impl InputEvent {
    /// Create a [`Pan`](Self::Pan) event.
    #[inline]
    pub fn pan(dx: f64, dy: f64) -> Self {
        Self::Pan {
            dx,
            dy,
            x: None,
            y: None,
        }
    }

    /// Create a [`Pan`](Self::Pan) event at a specific cursor location.
    #[inline]
    pub fn pan_at(dx: f64, dy: f64, x: f64, y: f64) -> Self {
        Self::Pan {
            dx,
            dy,
            x: Some(x),
            y: Some(y),
        }
    }

    /// Create a [`Zoom`](Self::Zoom) event that zooms **in**.
    ///
    /// `factor` should be `> 1.0`.  Values ? 0 will be ignored by the
    /// controller.
    #[inline]
    pub fn zoom_in(factor: f64) -> Self {
        Self::Zoom {
            factor,
            x: None,
            y: None,
        }
    }

    /// Create a [`Zoom`](Self::Zoom) event around a specific cursor location.
    #[inline]
    pub fn zoom_at(factor: f64, x: f64, y: f64) -> Self {
        Self::Zoom {
            factor,
            x: Some(x),
            y: Some(y),
        }
    }

    /// Create a [`Zoom`](Self::Zoom) event that zooms **out**.
    ///
    /// `factor` should be `> 1.0`; the reciprocal is stored so
    /// the controller sees a value in `(0, 1)`.
    #[inline]
    pub fn zoom_out(factor: f64) -> Self {
        Self::Zoom {
            factor: if factor > 0.0 { 1.0 / factor } else { 0.0 },
            x: None,
            y: None,
        }
    }

    /// Create a [`Rotate`](Self::Rotate) event.
    #[inline]
    pub fn rotate(delta_yaw: f64, delta_pitch: f64) -> Self {
        Self::Rotate {
            delta_yaw,
            delta_pitch,
        }
    }

    /// Create a [`Resize`](Self::Resize) event.
    #[inline]
    pub fn resize(width: u32, height: u32) -> Self {
        Self::Resize { width, height }
    }

    /// Create a [`Touch`](Self::Touch) event.
    #[inline]
    pub fn touch(id: u64, phase: TouchPhase, x: f64, y: f64) -> Self {
        Self::Touch(TouchContact { id, phase, x, y })
    }
}

// ---------------------------------------------------------------------------
// Classification helpers
// ---------------------------------------------------------------------------

impl InputEvent {
    /// Returns `true` if this is a [`Pan`](Self::Pan) event.
    #[inline]
    pub fn is_pan(&self) -> bool {
        matches!(self, Self::Pan { .. })
    }

    /// Returns `true` if this is a [`Zoom`](Self::Zoom) event.
    #[inline]
    pub fn is_zoom(&self) -> bool {
        matches!(self, Self::Zoom { .. })
    }

    /// Returns `true` if this is a [`Rotate`](Self::Rotate) event.
    #[inline]
    pub fn is_rotate(&self) -> bool {
        matches!(self, Self::Rotate { .. })
    }

    /// Returns `true` if this is a [`Resize`](Self::Resize) event.
    #[inline]
    pub fn is_resize(&self) -> bool {
        matches!(self, Self::Resize { .. })
    }

    /// Returns `true` if this is a [`Touch`](Self::Touch) event.
    #[inline]
    pub fn is_touch(&self) -> bool {
        matches!(self, Self::Touch(_))
    }
}

// ---------------------------------------------------------------------------
// Display
// ---------------------------------------------------------------------------

impl fmt::Display for InputEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Pan { dx, dy, x, y } => {
                if let (Some(px), Some(py)) = (x, y) {
                    write!(f, "Pan(dx={dx:.1}, dy={dy:.1}, at={px:.1},{py:.1})")
                } else {
                    write!(f, "Pan(dx={dx:.1}, dy={dy:.1})")
                }
            }
            Self::Zoom { factor, x, y } => {
                if let (Some(px), Some(py)) = (x, y) {
                    write!(f, "Zoom(factor={factor:.3}, at={px:.1},{py:.1})")
                } else {
                    write!(f, "Zoom(factor={factor:.3})")
                }
            }
            Self::Rotate {
                delta_yaw,
                delta_pitch,
            } => write!(f, "Rotate(yaw={delta_yaw:.4}, pitch={delta_pitch:.4})"),
            Self::Resize { width, height } => {
                write!(f, "Resize({width}x{height})")
            }
            Self::Touch(c) => {
                write!(
                    f,
                    "Touch(id={}, {:?}, {:.1},{:.1})",
                    c.id, c.phase, c.x, c.y
                )
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // -- Construction -----------------------------------------------------

    #[test]
    fn pan_constructor() {
        let e = InputEvent::pan(10.0, -5.0);
        assert_eq!(
            e,
            InputEvent::Pan {
                dx: 10.0,
                dy: -5.0,
                x: None,
                y: None,
            }
        );
    }

    #[test]
    fn zoom_in_constructor() {
        let e = InputEvent::zoom_in(2.0);
        assert_eq!(
            e,
            InputEvent::Zoom {
                factor: 2.0,
                x: None,
                y: None,
            }
        );
    }

    #[test]
    fn zoom_at_constructor() {
        let e = InputEvent::zoom_at(2.0, 10.0, 20.0);
        assert_eq!(
            e,
            InputEvent::Zoom {
                factor: 2.0,
                x: Some(10.0),
                y: Some(20.0),
            }
        );
    }

    #[test]
    fn zoom_out_constructor() {
        let e = InputEvent::zoom_out(2.0);
        assert_eq!(
            e,
            InputEvent::Zoom {
                factor: 0.5,
                x: None,
                y: None,
            }
        );
    }

    #[test]
    fn zoom_out_zero_factor() {
        let e = InputEvent::zoom_out(0.0);
        assert_eq!(
            e,
            InputEvent::Zoom {
                factor: 0.0,
                x: None,
                y: None,
            }
        );
    }

    #[test]
    fn rotate_constructor() {
        let e = InputEvent::rotate(0.1, 0.2);
        assert_eq!(
            e,
            InputEvent::Rotate {
                delta_yaw: 0.1,
                delta_pitch: 0.2
            }
        );
    }

    #[test]
    fn resize_constructor() {
        let e = InputEvent::resize(1920, 1080);
        assert_eq!(
            e,
            InputEvent::Resize {
                width: 1920,
                height: 1080
            }
        );
    }

    // -- Classification ---------------------------------------------------

    #[test]
    fn is_pan() {
        assert!(InputEvent::pan(1.0, 2.0).is_pan());
        assert!(!InputEvent::zoom_in(1.0).is_pan());
    }

    #[test]
    fn is_zoom() {
        assert!(InputEvent::zoom_in(1.0).is_zoom());
        assert!(!InputEvent::pan(0.0, 0.0).is_zoom());
    }

    #[test]
    fn is_rotate() {
        assert!(InputEvent::rotate(0.0, 0.0).is_rotate());
        assert!(!InputEvent::resize(0, 0).is_rotate());
    }

    #[test]
    fn is_resize() {
        assert!(InputEvent::resize(800, 600).is_resize());
        assert!(!InputEvent::rotate(0.0, 0.0).is_resize());
    }

    // -- Display ----------------------------------------------------------

    #[test]
    fn display_pan() {
        let s = format!("{}", InputEvent::pan(10.0, -5.0));
        assert!(s.contains("Pan"));
        assert!(s.contains("10.0"));
    }

    #[test]
    fn display_zoom() {
        let s = format!("{}", InputEvent::zoom_in(1.5));
        assert!(s.contains("Zoom"));
        assert!(s.contains("1.5"));
    }

    #[test]
    fn display_rotate() {
        let s = format!("{}", InputEvent::rotate(0.1, 0.2));
        assert!(s.contains("Rotate"));
    }

    #[test]
    fn display_resize() {
        let s = format!("{}", InputEvent::resize(1920, 1080));
        assert!(s.contains("1920"));
        assert!(s.contains("1080"));
    }

    // -- Equality / Copy --------------------------------------------------

    #[test]
    fn copy_semantics() {
        let a = InputEvent::pan(1.0, 2.0);
        let b = a; // Copy
        assert_eq!(a, b);
    }

    #[test]
    fn clone_eq() {
        let a = InputEvent::zoom_in(3.0);
        #[allow(clippy::clone_on_copy)]
        let b = a.clone();
        assert_eq!(a, b);
    }

    #[test]
    fn different_variants_not_equal() {
        assert_ne!(InputEvent::pan(0.0, 0.0), InputEvent::zoom_in(1.0));
    }
}