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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Dynamic image overlay layer — a georeferenced overlay with
//! frame-provider–driven content updates.
//!
//! This is the Rustial equivalent of MapLibre / Mapbox `video` and
//! `canvas` source types.  Rather than wrapping a DOM `<video>` or
//! `<canvas>` element, the layer holds a [`FrameProvider`] trait object
//! that supplies new RGBA8 frames on demand.
//!
//! ## Data flow
//!
//! ```text
//! FrameProvider::next_frame()
//!     |
//!     v
//! DynamicImageOverlayLayer   (holds latest frame + generation)
//!     |
//!     v
//! collect_image_overlays()   (polls provider, emits ImageOverlayData)
//!     |
//!     v
//! FrameOutput::image_overlays   (renderer consumes as textured quads)
//! ```
//!
//! ## Usage
//!
//! ```rust,ignore
//! use rustial_engine::{DynamicImageOverlayLayer, FrameProvider, FrameData, GeoCoord};
//!
//! struct TestProvider;
//! impl FrameProvider for TestProvider {
//!     fn next_frame(&mut self) -> Option<FrameData> {
//!         Some(FrameData {
//!             width: 64,
//!             height: 64,
//!             data: vec![255u8; 64 * 64 * 4],
//!         })
//!     }
//! }
//!
//! let corners = [
//!     GeoCoord::from_lat_lon(40.0, -74.0),
//!     GeoCoord::from_lat_lon(40.0, -73.0),
//!     GeoCoord::from_lat_lon(39.0, -73.0),
//!     GeoCoord::from_lat_lon(39.0, -74.0),
//! ];
//! let layer = DynamicImageOverlayLayer::new("video-feed", corners, Box::new(TestProvider));
//! ```

use crate::camera_projection::CameraProjection;
use crate::layer::{Layer, LayerId, LayerKind};
use crate::layers::image_overlay_layer::ImageOverlayData;
use rustial_math::GeoCoord;
use std::any::Any;
use std::sync::Arc;

// ---------------------------------------------------------------------------
// FrameProvider trait
// ---------------------------------------------------------------------------

/// A single RGBA8 frame returned by a [`FrameProvider`].
#[derive(Debug, Clone)]
pub struct FrameData {
    /// Image width in pixels.
    pub width: u32,
    /// Image height in pixels.
    pub height: u32,
    /// RGBA8 pixel data (length must equal `width * height * 4`).
    pub data: Vec<u8>,
}

/// Trait for dynamic frame sources (video decoders, canvas renderers,
/// procedural generators, etc.).
///
/// Implementations supply RGBA8 frames to a
/// [`DynamicImageOverlayLayer`].  The engine polls [`next_frame`] once
/// per frame while the layer is visible and [`is_animating`] returns
/// `true`.
///
/// [`next_frame`]: FrameProvider::next_frame
/// [`is_animating`]: FrameProvider::is_animating
pub trait FrameProvider: Send + Sync {
    /// Poll for the next frame.
    ///
    /// Return `Some(FrameData)` when new pixel data is available, or
    /// `None` to keep the previous frame.
    fn next_frame(&mut self) -> Option<FrameData>;

    /// Whether this source is currently animating.
    ///
    /// When `false`, the engine skips polling [`next_frame`] until
    /// the flag changes.  Defaults to `true`.
    ///
    /// [`next_frame`]: FrameProvider::next_frame
    fn is_animating(&self) -> bool {
        true
    }
}

/// A closure-based [`FrameProvider`] for convenience.
///
/// Wraps any `FnMut() -> Option<FrameData>` as a frame provider.
pub struct CallbackFrameProvider<F> {
    callback: F,
    animating: bool,
}

impl<F: FnMut() -> Option<FrameData> + Send + Sync> CallbackFrameProvider<F> {
    /// Create a new callback-based frame provider.
    pub fn new(callback: F) -> Self {
        Self {
            callback,
            animating: true,
        }
    }

    /// Set whether the provider is currently animating.
    pub fn set_animating(&mut self, animating: bool) {
        self.animating = animating;
    }
}

impl<F: FnMut() -> Option<FrameData> + Send + Sync> FrameProvider for CallbackFrameProvider<F> {
    fn next_frame(&mut self) -> Option<FrameData> {
        (self.callback)()
    }

    fn is_animating(&self) -> bool {
        self.animating
    }
}

/// Factory type for creating [`FrameProvider`] instances.
///
/// Used by [`VideoSource`](crate::style::VideoSource) and
/// [`CanvasSource`](crate::style::CanvasSource) in the style system to
/// produce frame providers when a style document is applied.
pub type FrameProviderFactory = Arc<dyn Fn() -> Box<dyn FrameProvider> + Send + Sync>;

// ---------------------------------------------------------------------------
// DynamicImageOverlayLayer
// ---------------------------------------------------------------------------

/// A georeferenced overlay with dynamic frame content.
///
/// This is the Rustial equivalent of MapLibre / Mapbox `video` and
/// `canvas` source types.  A [`FrameProvider`] supplies RGBA8 frames
/// which are rendered as a textured quad at the specified geographic
/// coordinates.
///
/// The layer caches the most recent frame and tracks a generation
/// counter for change detection.  Renderers see this layer through
/// the same [`ImageOverlayData`] path as [`ImageOverlayLayer`],
/// so no renderer changes are required.
///
/// [`ImageOverlayLayer`]: crate::layers::ImageOverlayLayer
pub struct DynamicImageOverlayLayer {
    id: LayerId,
    name: String,
    visible: bool,
    opacity: f32,
    /// Geographic corner coordinates (TL, TR, BR, BL).
    coordinates: [GeoCoord; 4],
    /// Cached frame dimensions.
    width: u32,
    height: u32,
    /// Cached RGBA8 pixel data from the last provider frame.
    data: Arc<Vec<u8>>,
    /// Monotonically increasing generation counter.
    generation: u64,
    /// Whether the first frame has been received.
    has_frame: bool,
    /// The frame provider that supplies dynamic content.
    provider: Box<dyn FrameProvider>,
}

impl std::fmt::Debug for DynamicImageOverlayLayer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DynamicImageOverlayLayer")
            .field("id", &self.id)
            .field("name", &self.name)
            .field("visible", &self.visible)
            .field("opacity", &self.opacity)
            .field("width", &self.width)
            .field("height", &self.height)
            .field("has_frame", &self.has_frame)
            .field("generation", &self.generation)
            .field("animating", &self.provider.is_animating())
            .finish()
    }
}

impl DynamicImageOverlayLayer {
    /// Create a new dynamic image overlay layer.
    ///
    /// `coordinates` must be in TL → TR → BR → BL order.
    pub fn new(
        name: impl Into<String>,
        coordinates: [GeoCoord; 4],
        provider: Box<dyn FrameProvider>,
    ) -> Self {
        Self {
            id: LayerId::next(),
            name: name.into(),
            visible: true,
            opacity: 1.0,
            coordinates,
            width: 0,
            height: 0,
            data: Arc::new(Vec::new()),
            generation: 0,
            has_frame: false,
            provider,
        }
    }

    /// Geographic corners (TL, TR, BR, BL).
    #[inline]
    pub fn coordinates(&self) -> &[GeoCoord; 4] {
        &self.coordinates
    }

    /// Update the geographic corners.
    pub fn set_coordinates(&mut self, coordinates: [GeoCoord; 4]) {
        self.coordinates = coordinates;
        self.generation = self.generation.wrapping_add(1);
    }

    /// Monotonic generation counter, bumped on coordinate or frame changes.
    #[inline]
    pub fn generation(&self) -> u64 {
        self.generation
    }

    /// Cached frame dimensions `(width, height)`.
    #[inline]
    pub fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Whether at least one frame has been received.
    #[inline]
    pub fn has_frame(&self) -> bool {
        self.has_frame
    }

    /// Poll the frame provider for new data.
    ///
    /// Returns `true` if a new frame was received and the cached data
    /// was updated.
    pub fn poll_frame(&mut self) -> bool {
        if !self.provider.is_animating() {
            return false;
        }
        if let Some(frame) = self.provider.next_frame() {
            debug_assert_eq!(
                frame.data.len(),
                (frame.width * frame.height * 4) as usize,
                "FrameData RGBA8 length must equal width * height * 4"
            );
            self.width = frame.width;
            self.height = frame.height;
            self.data = Arc::new(frame.data);
            self.generation = self.generation.wrapping_add(1);
            self.has_frame = true;
            true
        } else {
            false
        }
    }

    /// Produce renderer-ready overlay data by projecting geographic
    /// corners into the active world-space coordinate system.
    ///
    /// Returns `None` if no frame has been received yet.
    pub fn to_overlay_data(&self, projection: CameraProjection) -> Option<ImageOverlayData> {
        if !self.has_frame || self.width == 0 || self.height == 0 {
            return None;
        }
        let corners = [
            project_corner(&self.coordinates[0], projection),
            project_corner(&self.coordinates[1], projection),
            project_corner(&self.coordinates[2], projection),
            project_corner(&self.coordinates[3], projection),
        ];
        Some(ImageOverlayData {
            layer_id: self.id,
            corners,
            width: self.width,
            height: self.height,
            data: Arc::clone(&self.data),
            opacity: self.opacity,
        })
    }

    /// Access the underlying frame provider.
    pub fn provider(&self) -> &dyn FrameProvider {
        &*self.provider
    }

    /// Access the underlying frame provider mutably.
    pub fn provider_mut(&mut self) -> &mut dyn FrameProvider {
        &mut *self.provider
    }
}

fn project_corner(coord: &GeoCoord, projection: CameraProjection) -> [f64; 3] {
    let w = projection.project(coord);
    [w.position.x, w.position.y, w.position.z]
}

// ---------------------------------------------------------------------------
// Layer trait implementation
// ---------------------------------------------------------------------------

impl Layer for DynamicImageOverlayLayer {
    fn id(&self) -> LayerId {
        self.id
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn kind(&self) -> LayerKind {
        LayerKind::Custom
    }

    fn visible(&self) -> bool {
        self.visible
    }

    fn set_visible(&mut self, visible: bool) {
        self.visible = visible;
    }

    fn opacity(&self) -> f32 {
        self.opacity
    }

    fn set_opacity(&mut self, opacity: f32) {
        self.opacity = opacity.clamp(0.0, 1.0);
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

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

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

    struct CountingProvider {
        frame_count: u32,
        width: u32,
        height: u32,
    }

    impl CountingProvider {
        fn new(width: u32, height: u32) -> Self {
            Self {
                frame_count: 0,
                width,
                height,
            }
        }
    }

    impl FrameProvider for CountingProvider {
        fn next_frame(&mut self) -> Option<FrameData> {
            self.frame_count += 1;
            // Each frame has pixels filled with the frame count (mod 256).
            let fill = (self.frame_count % 256) as u8;
            Some(FrameData {
                width: self.width,
                height: self.height,
                data: vec![fill; (self.width * self.height * 4) as usize],
            })
        }
    }

    struct PausableProvider {
        animating: bool,
    }

    impl FrameProvider for PausableProvider {
        fn next_frame(&mut self) -> Option<FrameData> {
            Some(FrameData {
                width: 2,
                height: 2,
                data: vec![128; 16],
            })
        }

        fn is_animating(&self) -> bool {
            self.animating
        }
    }

    struct OneShotProvider {
        sent: bool,
    }

    impl FrameProvider for OneShotProvider {
        fn next_frame(&mut self) -> Option<FrameData> {
            if self.sent {
                None
            } else {
                self.sent = true;
                Some(FrameData {
                    width: 4,
                    height: 4,
                    data: vec![255; 64],
                })
            }
        }

        fn is_animating(&self) -> bool {
            !self.sent
        }
    }

    fn sample_corners() -> [GeoCoord; 4] {
        [
            GeoCoord::from_lat_lon(40.0, -74.0),
            GeoCoord::from_lat_lon(40.0, -73.0),
            GeoCoord::from_lat_lon(39.0, -73.0),
            GeoCoord::from_lat_lon(39.0, -74.0),
        ]
    }

    #[test]
    fn new_layer_starts_without_frame() {
        let layer = DynamicImageOverlayLayer::new(
            "test",
            sample_corners(),
            Box::new(CountingProvider::new(8, 8)),
        );
        assert!(!layer.has_frame());
        assert_eq!(layer.dimensions(), (0, 0));
        assert_eq!(layer.generation(), 0);
    }

    #[test]
    fn poll_frame_receives_first_frame() {
        let mut layer = DynamicImageOverlayLayer::new(
            "test",
            sample_corners(),
            Box::new(CountingProvider::new(8, 8)),
        );
        assert!(layer.poll_frame());
        assert!(layer.has_frame());
        assert_eq!(layer.dimensions(), (8, 8));
        assert_eq!(layer.generation(), 1);
    }

    #[test]
    fn consecutive_polls_bump_generation() {
        let mut layer = DynamicImageOverlayLayer::new(
            "test",
            sample_corners(),
            Box::new(CountingProvider::new(4, 4)),
        );
        layer.poll_frame();
        layer.poll_frame();
        layer.poll_frame();
        assert_eq!(layer.generation(), 3);
    }

    #[test]
    fn paused_provider_skips_poll() {
        let mut layer = DynamicImageOverlayLayer::new(
            "test",
            sample_corners(),
            Box::new(PausableProvider { animating: false }),
        );
        assert!(!layer.poll_frame());
        assert!(!layer.has_frame());
        assert_eq!(layer.generation(), 0);
    }

    #[test]
    fn one_shot_provider_stops_after_first() {
        let mut layer = DynamicImageOverlayLayer::new(
            "test",
            sample_corners(),
            Box::new(OneShotProvider { sent: false }),
        );
        assert!(layer.poll_frame());
        assert_eq!(layer.generation(), 1);
        // Provider is no longer animating.
        assert!(!layer.poll_frame());
        assert_eq!(layer.generation(), 1);
    }

    #[test]
    fn to_overlay_data_returns_none_without_frame() {
        let layer = DynamicImageOverlayLayer::new(
            "test",
            sample_corners(),
            Box::new(CountingProvider::new(4, 4)),
        );
        assert!(layer
            .to_overlay_data(CameraProjection::WebMercator)
            .is_none());
    }

    #[test]
    fn to_overlay_data_returns_some_after_poll() {
        let mut layer = DynamicImageOverlayLayer::new(
            "test",
            sample_corners(),
            Box::new(CountingProvider::new(4, 4)),
        );
        layer.poll_frame();
        let data = layer.to_overlay_data(CameraProjection::WebMercator);
        assert!(data.is_some());
        let data = data.unwrap();
        assert_eq!(data.width, 4);
        assert_eq!(data.height, 4);
        assert_eq!(data.data.len(), 64);
    }

    #[test]
    fn set_coordinates_bumps_generation() {
        let mut layer = DynamicImageOverlayLayer::new(
            "test",
            sample_corners(),
            Box::new(CountingProvider::new(4, 4)),
        );
        let g0 = layer.generation();
        layer.set_coordinates([
            GeoCoord::from_lat_lon(50.0, -75.0),
            GeoCoord::from_lat_lon(50.0, -74.0),
            GeoCoord::from_lat_lon(49.0, -74.0),
            GeoCoord::from_lat_lon(49.0, -75.0),
        ]);
        assert_eq!(layer.generation(), g0 + 1);
    }

    #[test]
    fn opacity_clamps_to_valid_range() {
        let mut layer = DynamicImageOverlayLayer::new(
            "test",
            sample_corners(),
            Box::new(CountingProvider::new(4, 4)),
        );
        layer.set_opacity(2.0);
        assert_eq!(layer.opacity(), 1.0);
        layer.set_opacity(-0.5);
        assert_eq!(layer.opacity(), 0.0);
    }

    #[test]
    fn callback_frame_provider_works() {
        let counter = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let counter_clone = counter.clone();
        let provider = CallbackFrameProvider::new(move || {
            let n = counter_clone.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            Some(FrameData {
                width: 2,
                height: 2,
                data: vec![(n % 256) as u8; 16],
            })
        });
        let mut layer = DynamicImageOverlayLayer::new("test", sample_corners(), Box::new(provider));
        layer.poll_frame();
        assert!(layer.has_frame());
        assert_eq!(counter.load(std::sync::atomic::Ordering::Relaxed), 1);
        layer.poll_frame();
        assert_eq!(counter.load(std::sync::atomic::Ordering::Relaxed), 2);
    }
}