1use std::sync::Arc;
6
7use glam::{DVec2, Vec2};
8use mln_style::feature::{GeometryCoordinate, GeometryCoordinates};
9use mln_style::geometry::Point;
10use mln_style::hash::{HashMap, HashSet};
11use smallvec::SmallVec;
12
13use super::grid::{Aabb, Grid, Shape};
14use crate::camera::View;
15use crate::geo::ScreenCoordinate;
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
22const VIEWPORT_PADDING_DEFAULT: f32 = 100.0;
27const VIEWPORT_PADDING_FOR_STATIC_TILES: f32 = 1024.0;
30const 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42pub enum Overlap {
43 #[default]
45 Never,
46 Always,
48 Cooperative,
50}
51
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
56pub struct CollisionGroup(Option<u16>);
57
58impl CollisionGroup {
59 pub const ALL: CollisionGroup = CollisionGroup(None);
61
62 fn id(self) -> u16 {
64 self.0.unwrap_or(0)
65 }
66
67 fn has(self, feature: &IndexedSubfeature) -> bool {
69 self.0.is_none_or(|group| feature.collision_group_id == group)
70 }
71}
72
73pub(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 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#[derive(Clone, Copy)]
99pub struct Item<'a> {
100 pub feature: &'a IndexedSubfeature,
102 pub record: u32,
105 pub overlap: Overlap,
108 pub ignore_placement: bool,
111 pub stands_at: Option<(Point<f64>, f64)>,
116}
117
118#[derive(Debug)]
120pub struct RetainedQueryData {
121 pub bucket_instance_id: u32,
122 pub feature_index: Option<Arc<FeatureIndex>>,
123 pub tile_id: OverscaledTileID,
124 pub source: SourceKey,
126 pub feature_sort_order: Option<Arc<Vec<usize>>>,
129}
130
131pub struct CollisionIndex {
137 view: View,
138 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 #[must_use]
156 pub fn new(view: &View, map_mode: MapMode) -> Self {
157 CollisionIndex::reusing(view, map_mode, None)
158 }
159
160 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 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 #[must_use]
197 pub fn view(&self) -> &View {
198 &self.view
199 }
200
201 #[must_use]
204 pub fn viewport_padding(&self) -> f32 {
205 self.viewport_padding
206 }
207
208 #[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 #[must_use]
222 pub fn to_viewport(&self, shape: Shape) -> Shape {
223 let padding = Vec2::splat(self.viewport_padding);
224 match shape {
225 Shape::Box(aabb) => Shape::Box(Aabb::new(aabb.min - padding, aabb.max - padding)),
226 Shape::Circle { center, radius } => Shape::Circle { center: center - padding, radius },
227 }
228 }
229
230 #[inline]
233 #[must_use]
234 pub fn is_offscreen(&self, bounds: &Aabb) -> bool {
235 bounds.max.x < self.viewport_padding
236 || bounds.min.x >= self.screen_right_boundary
237 || bounds.max.y < self.viewport_padding
238 || bounds.min.y >= self.screen_bottom_boundary
239 }
240
241 #[inline]
244 #[must_use]
245 pub fn is_inside_grid(&self, bounds: &Aabb) -> bool {
246 bounds.max.x >= 0.0
247 && bounds.min.x < self.grid_right_boundary
248 && bounds.max.y >= 0.0
249 && bounds.min.y < self.grid_bottom_boundary
250 }
251
252 #[inline]
255 #[must_use]
256 pub fn collides(&self, shape: &Shape, overlap: Overlap, group: CollisionGroup) -> bool {
257 match overlap {
258 Overlap::Never => self.collision_grid.any(shape, |feature| group.has(feature)),
259 Overlap::Always => false,
260 Overlap::Cooperative => {
261 self.collision_grid.any(shape, |feature| feature.overlap_mode == Overlap::Never && group.has(feature))
262 }
263 }
264 }
265
266 #[inline]
268 pub fn insert(&mut self, shapes: &[Option<Shape>], item: &Item<'_>, group: CollisionGroup) {
269 let grid = if item.ignore_placement { &mut self.ignored_grid } else { &mut self.collision_grid };
270 for shape in shapes.iter().flatten() {
271 let feature = IndexedSubfeature {
272 bucket_instance_id: item.record,
273 collision_group_id: group.id(),
274 overlap_mode: item.overlap,
275 stands_at: item.stands_at,
276 ..item.feature.clone()
277 };
278 grid.insert(feature, *shape);
279 }
280 }
281
282 pub fn retain(&mut self, record: u32, data: impl FnOnce() -> RetainedQueryData) {
285 self.retained_query_data.entry(record).or_insert_with(data);
286 }
287
288 pub fn set_query_order(&mut self, record: u32, order: Option<&Arc<Vec<usize>>>) {
291 if let Some(retained) = self.retained_query_data.get_mut(&record) {
292 retained.feature_sort_order = order.cloned();
293 }
294 }
295
296 pub(crate) fn query_data(&self, record: u32) -> Result<&RetainedQueryData, String> {
298 self.retained_query_data.get(&record).ok_or_else(|| format!("no query data of the bucket instance {record}"))
299 }
300
301 pub(crate) fn query_rendered(
304 &self,
305 query_geometry: &[ScreenCoordinate],
306 shows: impl Fn(&IndexedSubfeature) -> bool,
307 ) -> HashMap<u32, Vec<IndexedSubfeature>> {
308 let mut result: HashMap<u32, Vec<IndexedSubfeature>> = HashMap::default();
309 if query_geometry.is_empty() || (self.collision_grid.is_empty() && self.ignored_grid.is_empty()) {
310 return result;
311 }
312
313 let mut integer_query = GeometryCoordinates::with_capacity(query_geometry.len());
316 let mut envelope = Aabb::new(Vec2::INFINITY, Vec2::NEG_INFINITY);
317 for point in query_geometry {
318 let point = Vec2::new(point.x as f32, point.y as f32) + self.viewport_padding;
319 integer_query.push(Point::new(point.x as i16, point.y as i16));
320 envelope.min = envelope.min.min(point);
321 envelope.max = envelope.max.max(point);
322 }
323 let envelope = Shape::Box(envelope);
324
325 let features = self.collision_grid.query(&envelope).chain(self.ignored_grid.query(&envelope));
326 let mut seen_buckets: HashMap<u32, HashSet<usize>> = HashMap::default();
327 for (feature, shape) in features {
328 let seen_features = seen_buckets.entry(feature.bucket_instance_id).or_default();
330 if seen_features.contains(&feature.index) {
331 continue;
332 }
333
334 if !polygon_intersects_box(&integer_query, &shape.bounds()) || !shows(feature) {
335 continue;
336 }
337
338 seen_features.insert(feature.index);
339 result.entry(feature.bucket_instance_id).or_default().push(feature.clone());
340 }
341
342 result
343 }
344}
345
346fn polygon_intersects_box(polygon: &[GeometryCoordinate], bbox: &Aabb) -> bool {
350 let (min_x, min_y) = (bbox.min.x as i16, bbox.min.y as i16);
351 let (max_x, max_y) = (bbox.max.x as i16, bbox.max.y as i16);
352 let corners =
353 [Point::new(min_x, min_y), Point::new(max_x, min_y), Point::new(max_x, max_y), Point::new(min_x, max_y)];
354 polygon_intersects_polygon(polygon, &corners)
355}
356
357#[cfg(test)]
358mod tests {
359 use mln_style::size::Size;
360
361 use super::*;
362
363 fn feature() -> IndexedSubfeature {
364 IndexedSubfeature {
365 index: 0,
366 source_layer_name: Arc::from(""),
367 bucket_leader_id: Arc::from(""),
368 sort_index: 0,
369 bucket_instance_id: 0,
370 collision_group_id: 0,
371 overlap_mode: Overlap::Never,
372 stands_at: None,
373 }
374 }
375
376 fn collision_index() -> CollisionIndex {
377 let mut state = crate::camera::TransformState::default();
378 state.set_size(Size::new(512, 512));
379 CollisionIndex::new(state.view(), MapMode::Static)
380 }
381
382 fn insert(index: &mut CollisionIndex, overlap: Overlap, group: CollisionGroup) {
383 let projected = [Some(Shape::Box(Aabb::new(Vec2::splat(100.0), Vec2::splat(200.0))))];
384 let feature = feature();
385 let item = Item { feature: &feature, record: 1, overlap, ignore_placement: false, stands_at: None };
386 index.insert(&projected, &item, group);
387 }
388
389 fn collides(index: &CollisionIndex, overlap: Overlap, group: CollisionGroup) -> bool {
390 let projected = Shape::Box(Aabb::new(Vec2::splat(150.0), Vec2::splat(250.0)));
391 index.collides(&projected, overlap, group)
392 }
393
394 const ALL: CollisionGroup = CollisionGroup::ALL;
395
396 #[test]
397 fn modes_collide_with_a_never_box() {
398 let mut index = collision_index();
399 insert(&mut index, Overlap::Never, ALL);
400 assert!(collides(&index, Overlap::Never, ALL));
401 assert!(!collides(&index, Overlap::Always, ALL));
402 assert!(collides(&index, Overlap::Cooperative, ALL));
403 }
404
405 #[test]
406 fn only_never_collides_with_an_overlapping_box() {
407 for placed in [Overlap::Always, Overlap::Cooperative] {
408 let mut index = collision_index();
409 insert(&mut index, placed, ALL);
410 assert!(collides(&index, Overlap::Never, ALL), "never over {placed:?}");
411 assert!(!collides(&index, Overlap::Always, ALL), "always over {placed:?}");
412 assert!(!collides(&index, Overlap::Cooperative, ALL), "cooperative over {placed:?}");
413 }
414 }
415
416 #[test]
417 fn cooperative_keeps_the_collision_group() {
418 let mut index = collision_index();
419 insert(&mut index, Overlap::Never, CollisionGroup(Some(2)));
420 assert!(collides(&index, Overlap::Cooperative, CollisionGroup(Some(2))));
421 assert!(!collides(&index, Overlap::Cooperative, CollisionGroup(Some(3))));
422 assert!(collides(&index, Overlap::Never, CollisionGroup(Some(2))));
423 assert!(!collides(&index, Overlap::Never, CollisionGroup(Some(3))));
424 }
425
426 #[test]
427 fn sources_take_groups_unless_they_collide_across() {
428 let mut groups = CollisionGroups::new(false);
429 let (a, b) = (groups.get("a"), groups.get("b"));
430 assert_ne!(a, b);
431 assert_eq!(groups.get("a"), a);
432 assert_eq!(CollisionGroups::new(true).get("a"), ALL);
433 }
434}