Skip to main content

maplibre_native/
custom_geometry.rs

1use std::fmt;
2use std::os::raw::c_void;
3use std::panic::{AssertUnwindSafe, catch_unwind};
4use std::ptr;
5use std::sync::{Condvar, Mutex};
6
7use maplibre_native_core as maplibre_core;
8use maplibre_native_sys as sys;
9
10/// Canonical tile identity used by custom geometry source callbacks.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12#[non_exhaustive]
13pub struct CanonicalTileId {
14    pub z: u32,
15    pub x: u32,
16    pub y: u32,
17}
18
19impl CanonicalTileId {
20    pub const fn new(z: u32, x: u32, y: u32) -> Self {
21        Self { z, x, y }
22    }
23
24    pub(crate) fn from_native(raw: sys::mln_canonical_tile_id) -> Self {
25        Self {
26            z: raw.z,
27            x: raw.x,
28            y: raw.y,
29        }
30    }
31
32    pub(crate) fn to_native(self) -> sys::mln_canonical_tile_id {
33        sys::mln_canonical_tile_id {
34            z: self.z,
35            x: self.x,
36            y: self.y,
37        }
38    }
39}
40
41type TileCallback = dyn Fn(CanonicalTileId) + Send + Sync + 'static;
42
43/// Options used when adding a custom geometry source.
44///
45/// Custom geometry callbacks may run on native worker threads. Keep callbacks
46/// quick, and hand work back to the map owner thread before calling map APIs
47/// such as `set_custom_geometry_source_tile_data` or invalidation helpers.
48#[non_exhaustive]
49pub struct CustomGeometrySourceOptions {
50    fetch_tile: Box<TileCallback>,
51    cancel_tile: Option<Box<TileCallback>>,
52    /// Minimum zoom level at which the source produces tiles.
53    pub min_zoom: Option<f64>,
54    /// Maximum zoom level at which the source produces tiles.
55    pub max_zoom: Option<f64>,
56    /// Douglas-Peucker simplification tolerance in tile coordinate units.
57    pub tolerance: Option<f64>,
58    /// Tile extent in pixels, usually 512.
59    pub tile_size: Option<u32>,
60    /// Extra tile buffer in pixels for geometry that crosses tile edges.
61    pub buffer: Option<u32>,
62    /// Whether native clips geometries to tile bounds.
63    pub clip: Option<bool>,
64    /// Whether the source wraps horizontally across the antimeridian.
65    pub wrap: Option<bool>,
66}
67
68impl fmt::Debug for CustomGeometrySourceOptions {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.debug_struct("CustomGeometrySourceOptions")
71            .field("has_cancel_tile", &self.cancel_tile.is_some())
72            .field("min_zoom", &self.min_zoom)
73            .field("max_zoom", &self.max_zoom)
74            .field("tolerance", &self.tolerance)
75            .field("tile_size", &self.tile_size)
76            .field("buffer", &self.buffer)
77            .field("clip", &self.clip)
78            .field("wrap", &self.wrap)
79            .finish_non_exhaustive()
80    }
81}
82
83impl CustomGeometrySourceOptions {
84    pub fn new<F>(fetch_tile: F) -> Self
85    where
86        F: Fn(CanonicalTileId) + Send + Sync + 'static,
87    {
88        Self {
89            fetch_tile: Box::new(fetch_tile),
90            cancel_tile: None,
91            min_zoom: None,
92            max_zoom: None,
93            tolerance: None,
94            tile_size: None,
95            buffer: None,
96            clip: None,
97            wrap: None,
98        }
99    }
100
101    pub fn with_cancel_tile<F>(mut self, cancel_tile: F) -> Self
102    where
103        F: Fn(CanonicalTileId) + Send + Sync + 'static,
104    {
105        self.cancel_tile = Some(Box::new(cancel_tile));
106        self
107    }
108}
109
110#[derive(Debug, Default)]
111struct CallbackLifecycle {
112    active: usize,
113    closing: bool,
114    closed: bool,
115}
116
117pub(crate) struct CustomGeometrySourceState {
118    fetch_tile: Box<TileCallback>,
119    cancel_tile: Option<Box<TileCallback>>,
120    min_zoom: Option<f64>,
121    max_zoom: Option<f64>,
122    tolerance: Option<f64>,
123    tile_size: Option<u32>,
124    buffer: Option<u32>,
125    clip: Option<bool>,
126    wrap: Option<bool>,
127    lifecycle: Mutex<CallbackLifecycle>,
128    idle: Condvar,
129}
130
131impl fmt::Debug for CustomGeometrySourceState {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        f.debug_struct("CustomGeometrySourceState")
134            .finish_non_exhaustive()
135    }
136}
137
138impl CustomGeometrySourceState {
139    pub(crate) fn new(options: CustomGeometrySourceOptions) -> Box<Self> {
140        Box::new(Self {
141            fetch_tile: options.fetch_tile,
142            cancel_tile: options.cancel_tile,
143            min_zoom: options.min_zoom,
144            max_zoom: options.max_zoom,
145            tolerance: options.tolerance,
146            tile_size: options.tile_size,
147            buffer: options.buffer,
148            clip: options.clip,
149            wrap: options.wrap,
150            lifecycle: Mutex::new(CallbackLifecycle::default()),
151            idle: Condvar::new(),
152        })
153    }
154
155    pub(crate) fn descriptor(&self) -> sys::mln_custom_geometry_source_options {
156        maplibre_core::style::custom_geometry_source_options_to_native(
157            maplibre_core::style::CustomGeometrySourceDescriptorFields {
158                fetch_tile: Some(fetch_tile_trampoline),
159                cancel_tile: self
160                    .cancel_tile
161                    .as_ref()
162                    .map(|_| cancel_tile_trampoline as _),
163                user_data: ptr::from_ref(self).cast_mut().cast::<c_void>(),
164                min_zoom: self.min_zoom,
165                max_zoom: self.max_zoom,
166                tolerance: self.tolerance,
167                tile_size: self.tile_size,
168                buffer: self.buffer,
169                clip: self.clip,
170                wrap: self.wrap,
171            },
172        )
173    }
174
175    pub(crate) fn close(&self) {
176        let mut lifecycle = self
177            .lifecycle
178            .lock()
179            .unwrap_or_else(|poisoned| poisoned.into_inner());
180        if lifecycle.closed {
181            return;
182        }
183        lifecycle.closing = true;
184        while lifecycle.active != 0 {
185            lifecycle = self
186                .idle
187                .wait(lifecycle)
188                .unwrap_or_else(|poisoned| poisoned.into_inner());
189        }
190        lifecycle.closed = true;
191    }
192
193    fn invoke_fetch(&self, tile_id: CanonicalTileId) {
194        let Some(_guard) = self.enter_callback() else {
195            return;
196        };
197        let _ = catch_unwind(AssertUnwindSafe(|| (self.fetch_tile)(tile_id)));
198    }
199
200    fn invoke_cancel(&self, tile_id: CanonicalTileId) {
201        let Some(_guard) = self.enter_callback() else {
202            return;
203        };
204        if let Some(cancel_tile) = &self.cancel_tile {
205            let _ = catch_unwind(AssertUnwindSafe(|| cancel_tile(tile_id)));
206        }
207    }
208
209    fn enter_callback(&self) -> Option<CallbackGuard<'_>> {
210        let mut lifecycle = self
211            .lifecycle
212            .lock()
213            .unwrap_or_else(|poisoned| poisoned.into_inner());
214        if lifecycle.closing || lifecycle.closed {
215            return None;
216        }
217        lifecycle.active += 1;
218        Some(CallbackGuard { state: self })
219    }
220
221    fn exit_callback(&self) {
222        let mut lifecycle = self
223            .lifecycle
224            .lock()
225            .unwrap_or_else(|poisoned| poisoned.into_inner());
226        lifecycle.active -= 1;
227        if lifecycle.active == 0 {
228            self.idle.notify_all();
229        }
230    }
231}
232
233impl Drop for CustomGeometrySourceState {
234    fn drop(&mut self) {
235        self.close();
236    }
237}
238
239struct CallbackGuard<'a> {
240    state: &'a CustomGeometrySourceState,
241}
242
243impl Drop for CallbackGuard<'_> {
244    fn drop(&mut self) {
245        self.state.exit_callback();
246    }
247}
248
249unsafe extern "C" fn fetch_tile_trampoline(
250    user_data: *mut c_void,
251    tile_id: sys::mln_canonical_tile_id,
252) {
253    let Some(state) = ptr::NonNull::new(user_data.cast::<CustomGeometrySourceState>()) else {
254        return;
255    };
256    // SAFETY: user_data is installed from CustomGeometrySourceState::descriptor
257    // and remains valid until source/style/map teardown waits for in-flight callbacks.
258    unsafe { state.as_ref() }.invoke_fetch(CanonicalTileId::from_native(tile_id));
259}
260
261unsafe extern "C" fn cancel_tile_trampoline(
262    user_data: *mut c_void,
263    tile_id: sys::mln_canonical_tile_id,
264) {
265    let Some(state) = ptr::NonNull::new(user_data.cast::<CustomGeometrySourceState>()) else {
266        return;
267    };
268    // SAFETY: user_data is installed from CustomGeometrySourceState::descriptor
269    // and remains valid until source/style/map teardown waits for in-flight callbacks.
270    unsafe { state.as_ref() }.invoke_cancel(CanonicalTileId::from_native(tile_id));
271}
272
273#[cfg(test)]
274mod tests {
275    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
276    use std::sync::{Arc, Condvar, Mutex};
277    use std::time::Duration;
278
279    use super::*;
280
281    fn tile(z: u32, x: u32, y: u32) -> sys::mln_canonical_tile_id {
282        CanonicalTileId::new(z, x, y).to_native()
283    }
284
285    #[test]
286    // Spec coverage: BND-124.
287    fn custom_geometry_callbacks_invoke_fetch_and_cancel_with_copied_tile_id() {
288        let fetched = Arc::new(Mutex::new(Vec::new()));
289        let cancelled = Arc::new(Mutex::new(Vec::new()));
290        let fetched_callback = Arc::clone(&fetched);
291        let cancelled_callback = Arc::clone(&cancelled);
292        let state = CustomGeometrySourceState::new(
293            CustomGeometrySourceOptions::new(move |tile_id| {
294                fetched_callback.lock().unwrap().push(tile_id);
295            })
296            .with_cancel_tile(move |tile_id| {
297                cancelled_callback.lock().unwrap().push(tile_id);
298            }),
299        );
300        let descriptor = state.descriptor();
301
302        unsafe {
303            descriptor.fetch_tile.unwrap()(descriptor.user_data, tile(1, 2, 3));
304            descriptor.cancel_tile.unwrap()(descriptor.user_data, tile(4, 5, 6));
305        }
306
307        assert_eq!(
308            fetched.lock().unwrap().as_slice(),
309            &[CanonicalTileId::new(1, 2, 3)]
310        );
311        assert_eq!(
312            cancelled.lock().unwrap().as_slice(),
313            &[CanonicalTileId::new(4, 5, 6)]
314        );
315    }
316
317    #[test]
318    // Spec coverage: BND-121.
319    fn custom_geometry_callbacks_contain_panics() {
320        let cancel_called = Arc::new(AtomicBool::new(false));
321        let cancel_called_callback = Arc::clone(&cancel_called);
322        let state = CustomGeometrySourceState::new(
323            CustomGeometrySourceOptions::new(|_| panic!("fetch panic")).with_cancel_tile(
324                move |_| {
325                    cancel_called_callback.store(true, Ordering::SeqCst);
326                    panic!("cancel panic");
327                },
328            ),
329        );
330        let descriptor = state.descriptor();
331
332        unsafe {
333            descriptor.fetch_tile.unwrap()(descriptor.user_data, tile(0, 0, 0));
334            descriptor.cancel_tile.unwrap()(descriptor.user_data, tile(0, 0, 0));
335        }
336
337        assert!(cancel_called.load(Ordering::SeqCst));
338    }
339
340    #[test]
341    // Spec coverage: BND-124.
342    fn custom_geometry_state_release_waits_for_active_upcalls() {
343        let entered = Arc::new((Mutex::new(false), Condvar::new()));
344        let release = Arc::new((Mutex::new(false), Condvar::new()));
345        let closed = Arc::new(AtomicBool::new(false));
346        let close_attempts = Arc::new(AtomicUsize::new(0));
347        let entered_callback = Arc::clone(&entered);
348        let release_callback = Arc::clone(&release);
349        let state = CustomGeometrySourceState::new(CustomGeometrySourceOptions::new(move |_| {
350            let (entered_lock, entered_cvar) = &*entered_callback;
351            *entered_lock.lock().unwrap() = true;
352            entered_cvar.notify_all();
353
354            let (release_lock, release_cvar) = &*release_callback;
355            let released = release_lock.lock().unwrap();
356            let (_released, timeout) = release_cvar
357                .wait_timeout_while(released, Duration::from_secs(5), |released| !*released)
358                .unwrap();
359            assert!(!timeout.timed_out());
360        }));
361        let descriptor = state.descriptor();
362        let callback = descriptor.fetch_tile.unwrap();
363        let user_data = descriptor.user_data as usize;
364
365        std::thread::scope(|scope| {
366            scope.spawn(move || unsafe {
367                callback(user_data as *mut c_void, tile(1, 1, 1));
368            });
369            let (entered_lock, entered_cvar) = &*entered;
370            let entered_guard = entered_lock.lock().unwrap();
371            let (_entered_guard, timeout) = entered_cvar
372                .wait_timeout_while(entered_guard, Duration::from_secs(5), |entered| !*entered)
373                .unwrap();
374            assert!(!timeout.timed_out());
375
376            let closed_for_thread = Arc::clone(&closed);
377            let close_attempts_for_thread = Arc::clone(&close_attempts);
378            let state_ref = &*state;
379            scope.spawn(move || {
380                close_attempts_for_thread.fetch_add(1, Ordering::SeqCst);
381                state_ref.close();
382                closed_for_thread.store(true, Ordering::SeqCst);
383            });
384
385            std::thread::sleep(Duration::from_millis(50));
386            assert_eq!(close_attempts.load(Ordering::SeqCst), 1);
387            assert!(!closed.load(Ordering::SeqCst));
388            let (release_lock, release_cvar) = &*release;
389            *release_lock.lock().unwrap() = true;
390            release_cvar.notify_all();
391        });
392
393        assert!(closed.load(Ordering::SeqCst));
394        unsafe {
395            descriptor.fetch_tile.unwrap()(descriptor.user_data, tile(9, 9, 9));
396        }
397    }
398}