Skip to main content

mln_engine/placement/
index.rs

1//! The collision index of a placement: the shapes placed so far, which each
2//! shape placed after them may not collide with, and the features they stand
3//! for, which rendered-feature queries of the placement find.
4
5use std::sync::Arc;
6
7use geometry::Point;
8use glam::{DVec2, Vec2};
9use mln_style::feature::GeometryCoordinates;
10use mln_style::hash::{HashMap, HashSet};
11use smallvec::SmallVec;
12
13use super::grid::{Aabb, Grid, Shape};
14use crate::camera::View;
15use crate::geo::ScreenLineString;
16use crate::geo::intersection_tests::polygon_intersects_polygon;
17use crate::map::MapMode;
18use crate::query::feature_index::{FeatureIndex, IndexedSubfeature};
19use crate::tile::OverscaledTileID;
20use crate::worker::job::SourceKey;
21
22/// How far the grid reaches past each edge of the viewport, in pixels.
23/// Shapes that cross into the viewport change what shows near its edge, so
24/// the padding moves most of those changes offscreen; more padding steadies
25/// what shows, and costs more.
26const VIEWPORT_PADDING_DEFAULT: f32 = 100.0;
27/// The padding of a still image of a tile, which must be much larger so
28/// that what crosses the tile's borders isn't cut off.
29const VIEWPORT_PADDING_FOR_STATIC_TILES: f32 = 1024.0;
30/// The width of a grid cell, in pixels.
31const CELL_SIZE: f32 = 25.0;
32
33fn find_viewport_padding(view: &View, map_mode: MapMode) -> f32 {
34    if map_mode == MapMode::Tile {
35        return VIEWPORT_PADDING_FOR_STATIC_TILES;
36    }
37    if view.pitch() == 0.0 { VIEWPORT_PADDING_DEFAULT } else { VIEWPORT_PADDING_DEFAULT * 2.0 }
38}
39
40/// How a shape may overlap the shapes placed before it.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42pub enum Overlap {
43    /// Collides with every shape.
44    #[default]
45    Never,
46    /// Collides with none.
47    Always,
48    /// Collides only with the shapes placed with `Never`.
49    Cooperative,
50}
51
52/// The shapes a shape collides with: with the map's cross-source
53/// collisions, those of every layer; without, those of its own layer's
54/// source.
55#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
56pub struct CollisionGroup(Option<u16>);
57
58impl CollisionGroup {
59    /// The group of every shape, as with the map's cross-source collisions.
60    pub const ALL: CollisionGroup = CollisionGroup(None);
61
62    /// The id of the group's shapes in the grid: 0 for every group.
63    fn id(self) -> u16 {
64        self.0.unwrap_or(0)
65    }
66
67    /// Whether a shape of this group collides with `feature`.
68    fn has(self, feature: &IndexedSubfeature) -> bool {
69        self.0.is_none_or(|group| feature.collision_group_id == group)
70    }
71}
72
73/// The collision groups of the sources of a placement's layers.
74pub(crate) struct CollisionGroups<'a> {
75    ids: SmallVec<[&'a str; 4]>,
76    cross_source_collisions: bool,
77}
78
79impl<'a> CollisionGroups<'a> {
80    pub(crate) fn new(cross_source_collisions: bool) -> Self {
81        CollisionGroups { ids: SmallVec::new(), cross_source_collisions }
82    }
83
84    /// The group of the shapes of the layers on `source`.
85    pub(crate) fn get(&mut self, source: &'a str) -> CollisionGroup {
86        if self.cross_source_collisions {
87            return CollisionGroup(None);
88        }
89        let index = self.ids.iter().position(|id| *id == source).unwrap_or_else(|| {
90            self.ids.push(source);
91            self.ids.len() - 1
92        });
93        CollisionGroup(Some(index as u16 + 1))
94    }
95}
96
97/// What a shape inserted in a [`CollisionIndex`] stands for.
98#[derive(Clone, Copy)]
99pub struct Item<'a> {
100    /// The feature, as queries return it.
101    pub feature: &'a IndexedSubfeature,
102    /// The record of the feature's bucket ([`CollisionIndex::retain`]),
103    /// which queries look the feature up in.
104    pub record: u32,
105    /// How the shape was placed, which a later shape placed with
106    /// [`Overlap::Cooperative`] reads.
107    pub overlap: Overlap,
108    /// Whether the shape stays out of the way of the shapes placed after
109    /// it: they don't collide with it, and queries still find it.
110    pub ignore_placement: bool,
111    /// Where the shape's symbol stands, if it hides behind the ground as
112    /// the shaders draw it: the point of its tile it draws at, in tile units
113    /// (translated), and its height, in meters. Queries don't find a shape
114    /// that the ground in front of that point hides.
115    pub stands_at: Option<(Point<f64>, f64)>,
116}
117
118/// What queries of a placement read of a bucket whose shapes it placed.
119#[derive(Debug)]
120pub struct RetainedQueryData {
121    pub bucket_instance_id: u32,
122    pub feature_index: Option<Arc<FeatureIndex>>,
123    pub tile_id: OverscaledTileID,
124    /// The tile's source, whose feature state queries return.
125    pub source: SourceKey,
126    /// The order of the bucket's features as the bucket last sorted them,
127    /// for a bucket whose features sort by their position.
128    pub feature_sort_order: Option<Arc<Vec<usize>>>,
129}
130
131/// The shapes a placement places, in viewport pixels plus
132/// [`viewport_padding`](Self::viewport_padding) on each side: one grid that
133/// later shapes collide with, and one of the shapes placed with
134/// [`Item::ignore_placement`], which they don't. It keeps the query data of
135/// the buckets whose shapes it holds.
136pub struct CollisionIndex {
137    view: View,
138    /// The viewport's size, in pixels.
139    size: DVec2,
140
141    viewport_padding: f32,
142    collision_grid: Grid<IndexedSubfeature>,
143    ignored_grid: Grid<IndexedSubfeature>,
144
145    screen_right_boundary: f32,
146    screen_bottom_boundary: f32,
147    grid_right_boundary: f32,
148    grid_bottom_boundary: f32,
149
150    retained_query_data: HashMap<u32, RetainedQueryData>,
151}
152
153impl CollisionIndex {
154    /// An empty collision index of `view` in `map_mode`.
155    #[must_use]
156    pub fn new(view: &View, map_mode: MapMode) -> Self {
157        CollisionIndex::reusing(view, map_mode, None)
158    }
159
160    /// An empty collision index, as [`new`](Self::new) makes, that reuses
161    /// the grids of `previous`, an index placement no longer reads.
162    /// Placement makes one for every placement, and the grids' cells keep
163    /// their allocations while the viewport keeps its size.
164    pub(crate) fn reusing(view: &View, map_mode: MapMode, previous: Option<CollisionIndex>) -> Self {
165        let viewport_padding = find_viewport_padding(view, map_mode);
166        let size = view.size();
167        // The grid covers the viewport and its padding on each side.
168        let width = size.width as f32;
169        let height = size.height as f32;
170        let grid_width = width + 2.0 * viewport_padding;
171        let grid_height = height + 2.0 * viewport_padding;
172        let grid_size = Vec2::new(grid_width, grid_height);
173        let reset = |mut grid: Grid<IndexedSubfeature>| {
174            grid.reset(grid_size, CELL_SIZE);
175            grid
176        };
177        let (collision_grid, ignored_grid) = match previous {
178            Some(previous) => (reset(previous.collision_grid), reset(previous.ignored_grid)),
179            None => (Grid::new(grid_size, CELL_SIZE), Grid::new(grid_size, CELL_SIZE)),
180        };
181        CollisionIndex {
182            view: view.clone(),
183            size: DVec2::new(f64::from(size.width), f64::from(size.height)),
184            viewport_padding,
185            collision_grid,
186            ignored_grid,
187            screen_right_boundary: width + viewport_padding,
188            screen_bottom_boundary: height + viewport_padding,
189            grid_right_boundary: grid_width,
190            grid_bottom_boundary: grid_height,
191            retained_query_data: HashMap::default(),
192        }
193    }
194
195    /// The view the index places in.
196    #[must_use]
197    pub fn view(&self) -> &View {
198        &self.view
199    }
200
201    /// How far the grid reaches past each edge of the viewport, in pixels:
202    /// where a shape at the viewport's top-left corner is.
203    #[must_use]
204    pub fn viewport_padding(&self) -> f32 {
205        self.viewport_padding
206    }
207
208    /// Where `x` and `y`, a point in normalized device coordinates (y up),
209    /// are in the grid (y down).
210    #[inline]
211    #[must_use]
212    pub fn to_grid(&self, x: f64, y: f64) -> Vec2 {
213        let viewport_padding = f64::from(self.viewport_padding);
214        Vec2::new(
215            (f64::midpoint(x, 1.0) * self.size.x + viewport_padding) as f32,
216            (f64::midpoint(-y, 1.0) * self.size.y + viewport_padding) as f32,
217        )
218    }
219
220    /// Whether `bounds` are wholly outside the viewport, in its padding or
221    /// past it.
222    #[inline]
223    #[must_use]
224    pub fn is_offscreen(&self, bounds: &Aabb) -> bool {
225        bounds.max.x < self.viewport_padding
226            || bounds.min.x >= self.screen_right_boundary
227            || bounds.max.y < self.viewport_padding
228            || bounds.min.y >= self.screen_bottom_boundary
229    }
230
231    /// Whether `bounds` reach into the grid. A shape outside it can't place,
232    /// though [`collides`](Self::collides) doesn't say so.
233    #[inline]
234    #[must_use]
235    pub fn is_inside_grid(&self, bounds: &Aabb) -> bool {
236        bounds.max.x >= 0.0
237            && bounds.min.x < self.grid_right_boundary
238            && bounds.max.y >= 0.0
239            && bounds.min.y < self.grid_bottom_boundary
240    }
241
242    /// Whether `shape`, placed with `overlap`, collides with a shape of
243    /// `group` placed before it.
244    #[inline]
245    #[must_use]
246    pub fn collides(&self, shape: &Shape, overlap: Overlap, group: CollisionGroup) -> bool {
247        match overlap {
248            Overlap::Never => self.collision_grid.any(shape, |feature| group.has(feature)),
249            Overlap::Always => false,
250            Overlap::Cooperative => {
251                self.collision_grid.any(shape, |feature| feature.overlap_mode == Overlap::Never && group.has(feature))
252            }
253        }
254    }
255
256    /// Inserts `shapes`, which stand for `item`, in `group`.
257    #[inline]
258    pub fn insert(&mut self, shapes: &[Option<Shape>], item: &Item<'_>, group: CollisionGroup) {
259        let grid = if item.ignore_placement { &mut self.ignored_grid } else { &mut self.collision_grid };
260        for shape in shapes.iter().flatten() {
261            let feature = IndexedSubfeature {
262                bucket_instance_id: item.record,
263                collision_group_id: group.id(),
264                overlap_mode: item.overlap,
265                stands_at: item.stands_at,
266                ..item.feature.clone()
267            };
268            grid.insert(feature, *shape);
269        }
270    }
271
272    /// Keeps `data` for queries of the features of the bucket of `record`,
273    /// unless the index keeps the bucket's already.
274    pub fn retain(&mut self, record: u32, data: impl FnOnce() -> RetainedQueryData) {
275        self.retained_query_data.entry(record).or_insert_with(data);
276    }
277
278    /// Has queries return the features of the bucket of `record` in
279    /// `order`, if the index keeps its query data.
280    pub fn set_query_order(&mut self, record: u32, order: &Option<Arc<Vec<usize>>>) {
281        if let Some(retained) = self.retained_query_data.get_mut(&record) {
282            retained.feature_sort_order.clone_from(order);
283        }
284    }
285
286    /// The query data of a bucket instance; `Err` if there is none.
287    pub(crate) fn query_data(&self, record: u32) -> Result<&RetainedQueryData, String> {
288        self.retained_query_data.get(&record).ok_or_else(|| format!("no query data of the bucket instance {record}"))
289    }
290
291    /// The features whose shapes `query_geometry`, in viewport pixels,
292    /// touches and `shows` takes, by their record.
293    pub(crate) fn query_rendered(
294        &self,
295        query_geometry: &ScreenLineString,
296        shows: impl Fn(&IndexedSubfeature) -> bool,
297    ) -> HashMap<u32, Vec<IndexedSubfeature>> {
298        let mut result: HashMap<u32, Vec<IndexedSubfeature>> = HashMap::default();
299        if query_geometry.is_empty() || (self.collision_grid.is_empty() && self.ignored_grid.is_empty()) {
300            return result;
301        }
302
303        let mut grid_query: Vec<Point<f32>> = Vec::with_capacity(query_geometry.len());
304        for point in query_geometry {
305            grid_query.push(Point::new(point.x as f32 + self.viewport_padding, point.y as f32 + self.viewport_padding));
306        }
307
308        // The bounding box of the query in the grid.
309        let mut envelope = Aabb::new(Vec2::INFINITY, Vec2::NEG_INFINITY);
310        for point in &grid_query {
311            let point = Vec2::new(point.x, point.y);
312            envelope.min = envelope.min.min(point);
313            envelope.max = envelope.max.max(point);
314        }
315        let envelope = Shape::Box(envelope);
316
317        let features = self.collision_grid.query(&envelope).chain(self.ignored_grid.query(&envelope));
318        let mut seen_buckets: HashMap<u32, HashSet<usize>> = HashMap::default();
319        for (feature, shape) in features {
320            // Skip already seen features.
321            let seen_features = seen_buckets.entry(feature.bucket_instance_id).or_default();
322            if seen_features.contains(&feature.index) {
323                continue;
324            }
325
326            if !polygon_intersects_box(&grid_query, &shape.bounds()) || !shows(feature) {
327                continue;
328            }
329
330            seen_features.insert(feature.index);
331            result.entry(feature.bucket_instance_id).or_default().push(feature.clone());
332        }
333
334        result
335    }
336}
337
338fn polygon_intersects_box(polygon: &[Point<f32>], bbox: &Aabb) -> bool {
339    // The integer polygon test, whose conversion limits the query's accuracy
340    // to a pixel.
341    let mut integer_polygon = GeometryCoordinates::new();
342    for point in polygon {
343        integer_polygon.push(Point::new(point.x as i16, point.y as i16));
344    }
345    let min_x1 = bbox.min.x as i16;
346    let max_y1 = bbox.max.y as i16;
347    let min_y1 = bbox.min.y as i16;
348    let max_x1 = bbox.max.x as i16;
349
350    let bbox_points: GeometryCoordinates = vec![
351        Point::new(min_x1, min_y1),
352        Point::new(max_x1, min_y1),
353        Point::new(max_x1, max_y1),
354        Point::new(min_x1, max_y1),
355    ];
356
357    polygon_intersects_polygon(&integer_polygon, &bbox_points)
358}
359
360#[cfg(test)]
361mod tests {
362    use mln_style::size::Size;
363
364    use super::*;
365
366    fn feature() -> IndexedSubfeature {
367        IndexedSubfeature {
368            index: 0,
369            source_layer_name: Arc::from(""),
370            bucket_leader_id: Arc::from(""),
371            sort_index: 0,
372            bucket_instance_id: 0,
373            collision_group_id: 0,
374            overlap_mode: Overlap::Never,
375            stands_at: None,
376        }
377    }
378
379    fn collision_index() -> CollisionIndex {
380        let mut state = crate::camera::TransformState::default();
381        state.set_size(Size::new(512, 512));
382        CollisionIndex::new(state.view(), MapMode::Static)
383    }
384
385    fn insert(index: &mut CollisionIndex, overlap: Overlap, group: CollisionGroup) {
386        let projected = [Some(Shape::Box(Aabb::new(Vec2::splat(100.0), Vec2::splat(200.0))))];
387        let feature = feature();
388        let item = Item { feature: &feature, record: 1, overlap, ignore_placement: false, stands_at: None };
389        index.insert(&projected, &item, group);
390    }
391
392    fn collides(index: &CollisionIndex, overlap: Overlap, group: CollisionGroup) -> bool {
393        let projected = Shape::Box(Aabb::new(Vec2::splat(150.0), Vec2::splat(250.0)));
394        index.collides(&projected, overlap, group)
395    }
396
397    const ALL: CollisionGroup = CollisionGroup::ALL;
398
399    #[test]
400    fn modes_collide_with_a_never_box() {
401        let mut index = collision_index();
402        insert(&mut index, Overlap::Never, ALL);
403        assert!(collides(&index, Overlap::Never, ALL));
404        assert!(!collides(&index, Overlap::Always, ALL));
405        assert!(collides(&index, Overlap::Cooperative, ALL));
406    }
407
408    #[test]
409    fn only_never_collides_with_an_overlapping_box() {
410        for placed in [Overlap::Always, Overlap::Cooperative] {
411            let mut index = collision_index();
412            insert(&mut index, placed, ALL);
413            assert!(collides(&index, Overlap::Never, ALL), "never over {placed:?}");
414            assert!(!collides(&index, Overlap::Always, ALL), "always over {placed:?}");
415            assert!(!collides(&index, Overlap::Cooperative, ALL), "cooperative over {placed:?}");
416        }
417    }
418
419    #[test]
420    fn cooperative_keeps_the_collision_group() {
421        let mut index = collision_index();
422        insert(&mut index, Overlap::Never, CollisionGroup(Some(2)));
423        assert!(collides(&index, Overlap::Cooperative, CollisionGroup(Some(2))));
424        assert!(!collides(&index, Overlap::Cooperative, CollisionGroup(Some(3))));
425        assert!(collides(&index, Overlap::Never, CollisionGroup(Some(2))));
426        assert!(!collides(&index, Overlap::Never, CollisionGroup(Some(3))));
427    }
428
429    #[test]
430    fn sources_take_groups_unless_they_collide_across() {
431        let mut groups = CollisionGroups::new(false);
432        let (a, b) = (groups.get("a"), groups.get("b"));
433        assert_ne!(a, b);
434        assert_eq!(groups.get("a"), a);
435        assert_eq!(CollisionGroups::new(true).get("a"), ALL);
436    }
437}