Skip to main content

mln_engine/query/
feature_index.rs

1//! The index of a tile's features by their bounding boxes, which
2//! `queryRenderedFeatures` searches. A tile worker fills a
3//! [`FeatureIndexBuilder`] as it lays the tile out and finishes it into a
4//! [`FeatureIndex`], which is only read after. Most tiles are never queried,
5//! so the index builds its R-tree at its first query.
6
7use std::borrow::Cow;
8use std::cmp::Reverse;
9use std::sync::{Arc, OnceLock};
10
11use geo_index::rtree::sort::HilbertSort;
12use geo_index::rtree::{RTree, RTreeBuilder, RTreeIndex};
13use geometry::Point;
14use glam::Vec2;
15use mln_style::collections::VecMap;
16use mln_style::constants;
17use mln_style::error::Error;
18use mln_style::expression::{EvaluationContext, GlobalStateMap};
19use mln_style::feature::{
20    FeatureState, GeometryCollection, GeometryCoordinate, GeometryCoordinates, GeometryTileFeature,
21    convert_geometry_to_tile,
22};
23use mln_style::geo::WrapMode;
24use mln_style::hash::{HashMap, HashSet};
25use mln_style::tile_id::CanonicalTileID;
26use mln_style::types::{AlignmentType, CirclePitchScaleType, TranslateAnchorType};
27
28use crate::camera::{TileCoordinate, TileProjector, VerticalPerspectiveProjection, View};
29use crate::geo::ScreenCoordinate;
30use crate::layer::render_layer::RenderLayer;
31use crate::placement::Overlap;
32use crate::query::RenderedQueryOptions;
33use crate::source::source_state::SourceFeatureState;
34use crate::tile::feature::{Feature, feature_id_to_string};
35use crate::tile::{OverscaledTileID, TileData, UnwrappedTileID};
36
37/// The render layers a query looks at, by id.
38pub(crate) type QueryLayers<'a> = HashMap<String, &'a dyn RenderLayer>;
39
40/// What a query reads of a tile's features: those of its layers that its
41/// filter accepts, with their state.
42#[derive(Clone, Copy)]
43pub(crate) struct FeatureSelection<'a> {
44    pub(crate) layers: &'a QueryLayers<'a>,
45    pub(crate) options: &'a RenderedQueryOptions,
46    pub(crate) global_state: Option<&'a GlobalStateMap>,
47    pub(crate) tile_id: &'a OverscaledTileID,
48    pub(crate) feature_state: Option<&'a SourceFeatureState>,
49}
50
51/// The ground a frame drew of the terrain, which a query finds the features
52/// of some layers on.
53#[derive(Clone, Copy)]
54pub(crate) struct QueryGround<'a> {
55    pub(crate) elevation: &'a crate::render::terrain::TerrainElevation,
56    /// Whether the layers' points stand on the ground, rather than their
57    /// features lying on it. A point that stands shows raised, where the
58    /// query's lines of sight can meet the ground far beyond it, or not at
59    /// all, so every feature of a rendered tile is a candidate, and the
60    /// layer's hit test decides.
61    pub(crate) standing: bool,
62}
63
64/// Where a query looks in a tile: its geometry in tile units, seen through
65/// the camera.
66#[derive(Clone, Copy)]
67pub struct QueryRegion<'a> {
68    pub geometry: &'a GeometryCoordinates,
69    /// The screen points of `geometry`, from the view's top left: where the
70    /// query's lines of sight start.
71    pub screen: &'a [ScreenCoordinate],
72    /// Over terrain, the ground the frame drew under the tile, where the
73    /// lines of sight meet it at `geometry`, for the layers that stand on it.
74    pub ground: Option<crate::render::terrain::TileGround<'a>>,
75    /// Whether every feature of the tile is a candidate, rather than those
76    /// around `geometry` ([`QueryGround::standing`]).
77    pub(crate) whole_tile: bool,
78    pub view: &'a View,
79    pub projector: &'a TileProjector<'a>,
80    pub pixels_to_tile_units: f32,
81    /// How far around the geometry the layers' features may reach, in
82    /// pixels.
83    pub(crate) padding: f32,
84}
85
86/// What the hit tests of layers whose features stand at points share
87/// ([`Layer::hit`](crate::layer::Layer::hit)), as circles do.
88impl QueryRegion<'_> {
89    /// The height of the ground under `point` of the tile, in meters; 0
90    /// without ground.
91    #[must_use]
92    pub fn ground_height(&self, point: GeometryCoordinate) -> f64 {
93        self.ground.map_or(0.0, |ground| f64::from(ground.height(Vec2::new(f32::from(point.x), f32::from(point.y)))))
94    }
95
96    /// Where the query's lines of sight meet the plane `elevation` meters
97    /// up, in tile units, moved back by a layer's `translate` along the axes
98    /// of `anchor` ([`translate_query_geometry`]): the query of what lies in
99    /// that plane, aligned with the map.
100    #[must_use]
101    pub fn plane_geometry(
102        &self,
103        elevation: f64,
104        translate: [f32; 2],
105        anchor: TranslateAnchorType,
106    ) -> GeometryCoordinates {
107        let height = f64::from(self.view.size().height);
108        let plane: GeometryCoordinates = self
109            .screen
110            .iter()
111            .filter_map(|p| {
112                let up = ScreenCoordinate::new(p.x, height - p.y);
113                let location = self.view.screen_coordinate_to_lat_lng_at(&up, elevation, WrapMode::Unwrapped).ok()?;
114                let world = TileCoordinate::from_lat_lng(0.0, &location).p;
115                Some(TileCoordinate::to_geometry_coordinate(self.projector.tile_id(), &world))
116            })
117            .collect();
118        let bearing = self.view.angle() as f32;
119        translate_query_geometry(&plane, translate, anchor, bearing, self.pixels_to_tile_units).unwrap_or(plane)
120    }
121
122    /// Where `point`, in tile units, `elevation` meters up, shows in the
123    /// view, in pixels from its bottom left.
124    #[must_use]
125    pub fn viewport_point(&self, point: Point<f64>, elevation: f64) -> Vec2 {
126        let clip = self.projector.project(&point, elevation).point;
127        let size = self.view.size();
128        Vec2::new((clip.x as f32 + 1.0) * size.width as f32 * 0.5, (clip.y as f32 + 1.0) * size.height as f32 * 0.5)
129    }
130
131    /// `size`, of what stands at `point`, `elevation` meters up, scaled by
132    /// how far that is from the camera as `pitch_scale` says for
133    /// `pitch_alignment`: aligned with the map, a size kept in the
134    /// viewport's pixels grows with the distance in the map's plane; aligned
135    /// with the viewport, a size kept in the map's pixels shrinks with it.
136    #[must_use]
137    pub fn pitch_scaled_size(
138        &self,
139        size: f32,
140        point: GeometryCoordinate,
141        elevation: f64,
142        pitch_scale: CirclePitchScaleType,
143        pitch_alignment: AlignmentType,
144    ) -> f32 {
145        let point = Point::new(f64::from(point.x), f64::from(point.y));
146        let distance = self.projector.project(&point, elevation).signed_distance_from_camera;
147        let camera_distance = self.view.camera_to_center_distance();
148        match (pitch_scale, pitch_alignment) {
149            (CirclePitchScaleType::Viewport, AlignmentType::Map) => size * (distance / camera_distance) as f32,
150            (CirclePitchScaleType::Map, AlignmentType::Viewport) => size * (camera_distance / distance) as f32,
151            _ => size,
152        }
153    }
154
155    /// Whether what stands at `drawn`, where its layer draws it in tile
156    /// units (translated), `elevation` meters up, and hides behind the
157    /// ground, shows as the shaders draw it: in front of the globe's
158    /// horizon, through the projection as blended, and over terrain where
159    /// the ground in front of it fades it less than halfway
160    /// ([`TileGround::visibility`](crate::render::terrain::TileGround::visibility)).
161    #[must_use]
162    pub fn shows(&self, drawn: Point<f64>, elevation: f64) -> bool {
163        if self.view.is_globe() && self.projector.project_as_drawn(&drawn, elevation).occluded {
164            return false;
165        }
166        self.ground.is_none_or(|ground| ground.visibility(self.view, drawn, elevation) >= 0.5)
167    }
168}
169
170/// How many times its padding a query reaches past its geometry in `tile`
171/// for the features aligned with the map: on the globe, which draws them
172/// the same size everywhere, they span more of the tile's units away from
173/// the equator, the most at the tile's edge nearest a pole
174/// ([`Projection::map_aligned_scale_at`](crate::camera::Projection::map_aligned_scale_at));
175/// 1 on Mercator.
176pub(crate) fn map_aligned_padding_scale(view: &View, tile: &UnwrappedTileID) -> f64 {
177    [0.0, f64::from(constants::EXTENT)]
178        .map(|y| view.projection().map_aligned_scale_at(view, &Point::new(0.0, y), tile))
179        .into_iter()
180        .fold(1.0, f64::max)
181}
182
183/// The screen points, from the top left of `view`, that a query of
184/// `geometry` tests. A geometry's edges are followed in steps where its
185/// corners alone would cut off part of what it covers: past the globe's
186/// limb, where a point stands for the nearest horizon point, and over
187/// terrain (`over_terrain`), where the ground an edge passes over doesn't
188/// lie between the ground under its ends.
189pub(crate) fn query_screen_geometry<'a>(
190    view: &View,
191    geometry: &'a [ScreenCoordinate],
192    over_terrain: bool,
193) -> Cow<'a, [ScreenCoordinate]> {
194    const STEPS: i32 = 32;
195    let height = f64::from(view.size().height);
196    let on_planet = |p: &ScreenCoordinate| {
197        VerticalPerspectiveProjection::screen_coordinate_hits_globe(
198            view,
199            &ScreenCoordinate::new(p.x, height - p.y),
200            0.0,
201        )
202    };
203    let past_limb = || view.is_globe() && !geometry.iter().all(on_planet);
204    if geometry.len() < 2 || !(over_terrain || past_limb()) {
205        return Cow::Borrowed(geometry);
206    }
207    let mut traced = Vec::with_capacity((geometry.len() - 1) * STEPS as usize + 1);
208    for edge in geometry.windows(2) {
209        let (from, to) = (edge[0], edge[1]);
210        for k in 0..STEPS {
211            let t = f64::from(k) / f64::from(STEPS);
212            traced.push(ScreenCoordinate::new(from.x + (to.x - from.x) * t, from.y + (to.y - from.y) * t));
213        }
214    }
215    traced.extend(geometry.last().copied());
216    Cow::Owned(traced)
217}
218
219/// The features a query found, by layer id.
220pub(crate) type QueryResults = HashMap<String, Vec<Feature>>;
221
222/// The deepest tile, down to zoom 13, that holds all of `geometry`: where a
223/// query's filter places a feature that has no tile, as `within` and
224/// `distance` need. The geometry's coordinates in the zoom-0 tile, 2^13
225/// units wide, choose the tile exactly down to there, where a unit of the
226/// tile is under a metre. A geometry that reaches past the Mercator world,
227/// as past 85.05° or across the antimeridian, is in the zoom-0 tile, the
228/// only one whose units hold it.
229pub(crate) fn tile_holding(geometry: &geo_types::Geometry<f64>) -> CanonicalTileID {
230    const DEEPEST: u8 = 13;
231    let world = CanonicalTileID::new(0, 0, 0);
232    let points = convert_geometry_to_tile(geometry, &world);
233    let inside = 0..constants::EXTENT as i16;
234    let (mut min, mut max) = ((u32::MAX, u32::MAX), (0, 0));
235    for point in points.iter().flatten() {
236        if !inside.contains(&point.x) || !inside.contains(&point.y) {
237            return world;
238        }
239        let (x, y) = (u32::from(point.x.unsigned_abs()), u32::from(point.y.unsigned_abs()));
240        (min, max) = ((min.0.min(x), min.1.min(y)), (max.0.max(x), max.1.max(y)));
241    }
242    if min.0 > max.0 {
243        return world;
244    }
245    let tile = |z: u8| (min.0 >> (DEEPEST - z), min.1 >> (DEEPEST - z));
246    let holds = |z: u8| tile(z) == (max.0 >> (DEEPEST - z), max.1 >> (DEEPEST - z));
247    let z = (0..=DEEPEST).rev().find(|&z| holds(z)).unwrap_or(0);
248    let (x, y) = tile(z);
249    CanonicalTileID::new(z, x, y)
250}
251
252/// A feature of a feature index or a collision index, which a query looks
253/// up in its tile's data.
254#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
255pub struct IndexedSubfeature {
256    /// The feature's index in its source layer.
257    pub index: usize,
258    /// The feature's source layer.
259    pub source_layer_name: Arc<str>,
260    /// The id of the layer that leads the bucket the feature is in.
261    pub bucket_leader_id: Arc<str>,
262    /// Where the feature is among those the bucket indexed, which results
263    /// sort by.
264    pub sort_index: usize,
265    /// The record of the bucket of a feature in a collision index
266    /// ([`Item::record`](crate::placement::Item::record)); 0 elsewhere.
267    pub bucket_instance_id: u32,
268    /// The id of the collision group a collision index placed the feature
269    /// in; 0 elsewhere.
270    pub collision_group_id: u16,
271    /// How a collision index placed the feature's shapes. Only a collision
272    /// index sets it, so the worker codec doesn't carry it.
273    #[wire(skip)]
274    pub overlap_mode: Overlap,
275    /// Where a collision index's shape of the feature stands, if it hides
276    /// behind the ground ([`Item::stands_at`](crate::placement::Item::stands_at)).
277    /// Only a collision index sets it.
278    #[wire(skip)]
279    pub stands_at: Option<(Point<f64>, f64)>,
280}
281
282/// A box of a feature index: one ring of a feature.
283#[derive(Clone, Debug, PartialEq)]
284struct Entry {
285    /// The feature's index in its source layer.
286    index: usize,
287    /// The order the feature was inserted in; a query returns later features
288    /// first.
289    sort_index: usize,
290    source_layer_name: Arc<str>,
291    bucket_leader_id: Arc<str>,
292}
293
294/// A box's min x, min y, max x and max y, in tile units.
295type Bounds = [i16; 4];
296
297/// A feature index as a tile's layout fills it.
298pub(crate) struct FeatureIndexBuilder {
299    /// The rings' entries and boxes, in insertion order.
300    entries: Vec<Entry>,
301    boxes: Vec<Bounds>,
302    sort_index: usize,
303    source_layer_names: HashSet<Arc<str>>,
304    bucket_layer_ids: HashMap<Arc<str>, Vec<String>>,
305    tile_data: Option<TileData>,
306}
307
308impl FeatureIndexBuilder {
309    /// An empty index of `tile_data`'s features, sharing the tile data.
310    #[must_use]
311    pub(crate) fn new(tile_data: Option<TileData>) -> Self {
312        FeatureIndexBuilder {
313            entries: Vec::new(),
314            boxes: Vec::new(),
315            sort_index: 0,
316            source_layer_names: HashSet::default(),
317            bucket_layer_ids: HashMap::default(),
318            tile_data,
319        }
320    }
321
322    fn intern_layer_name(&mut self, name: &str) -> Arc<str> {
323        if let Some(existing) = self.source_layer_names.get(name) {
324            return Arc::clone(existing);
325        }
326        let name: Arc<str> = Arc::from(name);
327        self.source_layer_names.insert(Arc::clone(&name));
328        name
329    }
330
331    fn intern_leader_id(&mut self, id: &str) -> Arc<str> {
332        if let Some((existing, _)) = self.bucket_layer_ids.get_key_value(id) {
333            return Arc::clone(existing);
334        }
335        let id: Arc<str> = Arc::from(id);
336        self.bucket_layer_ids.insert(Arc::clone(&id), Vec::new());
337        id
338    }
339
340    /// Records the layers of the bucket whose leader is `bucket_leader_id`,
341    /// which a query of the bucket's features looks at.
342    pub(crate) fn set_bucket_layer_ids(&mut self, bucket_leader_id: &str, layer_ids: &[String]) {
343        let key = self.intern_leader_id(bucket_leader_id);
344        self.bucket_layer_ids.insert(key, layer_ids.to_vec());
345    }
346
347    /// Adds the feature at `index` of `source_layer_name`, with the box of
348    /// each of its rings that reaches into the tile.
349    pub(crate) fn insert(
350        &mut self,
351        geometries: &GeometryCollection,
352        index: usize,
353        source_layer_name: &str,
354        bucket_leader_id: &str,
355    ) {
356        let source_layer_name = self.intern_layer_name(source_layer_name);
357        let bucket_leader_id = self.intern_leader_id(bucket_leader_id);
358        let sort_index = self.sort_index;
359        self.sort_index += 1;
360        for ring in geometries.iter() {
361            let Some((min, max)) = envelope(ring.iter().copied()) else {
362                continue;
363            };
364            let extent = constants::EXTENT;
365            if i32::from(min.x) < extent && i32::from(min.y) < extent && max.x >= 0 && max.y >= 0 {
366                self.entries.push(Entry {
367                    index,
368                    sort_index,
369                    source_layer_name: Arc::clone(&source_layer_name),
370                    bucket_leader_id: Arc::clone(&bucket_leader_id),
371                });
372                self.boxes.push([min.x, min.y, max.x, max.y]);
373            }
374        }
375    }
376
377    /// The index of the features inserted.
378    #[must_use]
379    pub(crate) fn finish(self) -> FeatureIndex {
380        FeatureIndex {
381            tree: OnceLock::new(),
382            entries: self.entries,
383            boxes: self.boxes,
384            bucket_layer_ids: self.bucket_layer_ids,
385            tile_data: self.tile_data,
386        }
387    }
388}
389
390/// An R-tree of `boxes`, whose items are their indices; `None` if there are
391/// none. It holds the coordinates as `i32`, as sorting sums them.
392fn build_tree(boxes: &[Bounds]) -> Option<RTree<i32>> {
393    if boxes.is_empty() {
394        return None;
395    }
396    let mut builder = RTreeBuilder::new(boxes.len() as u32);
397    for &bounds in boxes {
398        let [min_x, min_y, max_x, max_y] = bounds.map(i32::from);
399        builder.add(min_x, min_y, max_x, max_y);
400    }
401    Some(builder.finish::<HilbertSort>())
402}
403
404/// A tile's features by their bounding boxes, and the tile data they are in.
405pub struct FeatureIndex {
406    /// Indexes `boxes`, once a query has built it; `None` when there are
407    /// none.
408    tree: OnceLock<Option<RTree<i32>>>,
409    /// The rings' entries and boxes, in insertion order.
410    entries: Vec<Entry>,
411    boxes: Vec<Bounds>,
412    bucket_layer_ids: HashMap<Arc<str>, Vec<String>>,
413    tile_data: Option<TileData>,
414}
415
416impl std::fmt::Debug for FeatureIndex {
417    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
418        f.debug_struct("FeatureIndex")
419            .field("entries", &self.entries.len())
420            .field("bucket_layer_ids", &self.bucket_layer_ids)
421            .finish_non_exhaustive()
422    }
423}
424
425/// The bounding box (min, max) of int16 points; `None` if there are none.
426fn envelope(points: impl IntoIterator<Item = GeometryCoordinate>) -> Option<(GeometryCoordinate, GeometryCoordinate)> {
427    let mut iter = points.into_iter();
428    let first = iter.next()?;
429    let (mut min, mut max) = (first, first);
430    for p in iter {
431        min.x = min.x.min(p.x);
432        min.y = min.y.min(p.y);
433        max.x = max.x.max(p.x);
434        max.y = max.y.max(p.y);
435    }
436    Some((min, max))
437}
438
439impl FeatureIndex {
440    #[must_use]
441    pub(crate) fn data(&self) -> Option<&TileData> {
442        self.tile_data.as_ref()
443    }
444
445    /// Sets the tile data the index's features are in.
446    pub(crate) fn set_data(&mut self, tile_data: Option<TileData>) {
447        self.tile_data = tile_data;
448    }
449
450    /// Adds the features of `selection` that `region` touches to `result`,
451    /// later features first.
452    pub(crate) fn query(
453        &self,
454        result: &mut QueryResults,
455        selection: &FeatureSelection<'_>,
456        region: &QueryRegion<'_>,
457    ) -> Result<(), Error> {
458        if self.tile_data.is_none() {
459            return Ok(());
460        }
461        let Some(tree) = self.tree.get_or_init(|| build_tree(&self.boxes)) else {
462            return Ok(());
463        };
464
465        let globe_scale = map_aligned_padding_scale(region.view, region.projector.tile_id()) as f32;
466        let additional_padding =
467            (region.padding * region.pixels_to_tile_units * globe_scale).min(constants::EXTENT as f32) as i16;
468        let whole_tile = || {
469            let extent = constants::EXTENT as i16;
470            (GeometryCoordinate::new(0, 0), GeometryCoordinate::new(extent, extent))
471        };
472        let candidates = if region.whole_tile { Some(whole_tile()) } else { envelope(region.geometry.iter().copied()) };
473        let Some((min, max)) = candidates else {
474            return Ok(());
475        };
476        // The padded box's corners are tile coordinates, which wrap in i16.
477        let (min_x, min_y) = (min.x.wrapping_sub(additional_padding), min.y.wrapping_sub(additional_padding));
478        let (max_x, max_y) = (max.x.wrapping_add(additional_padding), max.y.wrapping_add(additional_padding));
479        // Only a box that reaches into the tile finds features, and one that
480        // wrapped around is empty.
481        let extent = constants::EXTENT;
482        if min_x > max_x
483            || min_y > max_y
484            || max_x < 0
485            || max_y < 0
486            || i32::from(min_x) >= extent
487            || i32::from(min_y) >= extent
488        {
489            return Ok(());
490        }
491        let mut features: Vec<&Entry> = tree
492            .search(i32::from(min_x), i32::from(min_y), i32::from(max_x), i32::from(max_y))
493            .into_iter()
494            .filter_map(|i| self.entries.get(i as usize))
495            .collect();
496        // Later features first, each once.
497        features.sort_unstable_by_key(|feature| Reverse(feature.sort_index));
498        features.dedup_by_key(|feature| feature.sort_index);
499        for feature in features {
500            let entry = (feature.index, &*feature.source_layer_name, &*feature.bucket_leader_id);
501            self.add_feature(result, entry, selection, Some(region))?;
502        }
503        Ok(())
504    }
505
506    /// The features of `symbol_features`, which the collision index found,
507    /// that `selection` selects, in the order their bucket last drew them.
508    pub(crate) fn lookup_symbol_features(
509        &self,
510        symbol_features: &[IndexedSubfeature],
511        selection: &FeatureSelection<'_>,
512        feature_sort_order: Option<&Arc<Vec<usize>>>,
513    ) -> Result<QueryResults, Error> {
514        let mut result = QueryResults::default();
515        if self.tile_data.is_none() {
516            return Ok(result);
517        }
518        let mut sorted_features: Vec<&IndexedSubfeature> = symbol_features.iter().collect();
519
520        sorted_features.sort_by(|a, b| {
521            // Same idea as the non-symbol sort order, but symbol features may
522            // have changed their sort order since their indexed subfeature
523            // was added to the collision index. The feature sort order is
524            // relatively inefficient for querying but cheap to build on every
525            // bucket sort.
526            if let Some(order) = feature_sort_order {
527                // A query of rendered symbols returns features in
528                // top-to-bottom rendering order, last to first.
529                // Actually there can be multiple symbol instances per feature, so
530                // we sort each feature based on the first matching symbol instance.
531                let sorted_a = order.iter().position(|&i| i == a.index).unwrap_or(order.len());
532                let sorted_b = order.iter().position(|&i| i == b.index).unwrap_or(order.len());
533                debug_assert_ne!(sorted_a, order.len());
534                debug_assert_ne!(sorted_b, order.len());
535                sorted_b.cmp(&sorted_a)
536            } else {
537                // Bucket hasn't been re-sorted based on angle, so use same
538                // "reverse of appearance in source data" logic as non-symboles
539                b.sort_index.cmp(&a.sort_index)
540            }
541        });
542
543        for feature in sorted_features {
544            let entry = (feature.index, &*feature.source_layer_name, &*feature.bucket_leader_id);
545            self.add_feature(&mut result, entry, selection, None)?;
546        }
547        Ok(result)
548    }
549
550    /// Adds the feature `index` of the source layer `source_layer_name`,
551    /// of the bucket of `bucket_leader_id`, to `result` under each layer of
552    /// `selection` it is in, where it touches `region`. A symbol layer's
553    /// features need no region: the collision index found them.
554    fn add_feature(
555        &self,
556        result: &mut QueryResults,
557        (index, source_layer_name, bucket_leader_id): (usize, &str, &str),
558        selection: &FeatureSelection<'_>,
559        region: Option<&QueryRegion<'_>>,
560    ) -> Result<(), Error> {
561        let FeatureSelection { layers, options, global_state, tile_id, feature_state } = *selection;
562        let Some(tile_data) = &self.tile_data else {
563            return Ok(());
564        };
565        // Every leader the index holds has its bucket's layers.
566        let Some(layer_ids) = self.bucket_layer_ids.get(bucket_leader_id) else {
567            debug_assert!(false, "unknown bucket leader {bucket_leader_id}");
568            return Ok(());
569        };
570
571        // The source layer, the feature and its state are the same for every
572        // layer of the bucket: they are read once, where one of its layers
573        // is queried.
574        if !layer_ids.iter().any(|layer_id| layers.contains_key(layer_id)) {
575            return Ok(());
576        }
577        let Some(source_layer) = tile_data.layer(source_layer_name)? else {
578            debug_assert!(false, "source layer {source_layer_name} missing");
579            return Ok(());
580        };
581        let feature = source_layer.feature(index)?;
582        let geometry = feature.geometry()?;
583        let source_layer_id = source_layer.name().to_owned();
584        let mut state = FeatureState::default();
585        if let Some(source_feature_state) = feature_state
586            && let Some(id_str) = feature_id_to_string(&feature.get_id())
587        {
588            state = source_feature_state.state(Some(&source_layer_id), &id_str);
589        }
590
591        for layer_id in layer_ids {
592            let Some(render_layer) = layers.get(layer_id) else {
593                continue;
594            };
595
596            let needs_cross_tile_index = render_layer.base().evaluated_properties.entry().places();
597            // we use the float camera zoom here, not the integer tile ID zoom,
598            // because for the query we take into account the actual rendered
599            // size of the geometry (#2781)
600            let intersects = needs_cross_tile_index
601                || region.is_some_and(|region| render_layer.hit(region, &feature, &geometry, &state));
602            if !intersects {
603                continue;
604            }
605
606            // Match layer filters and source queries, including overzoomed tiles.
607            if let Some(filter) = &options.filter {
608                let context = EvaluationContext::with_zoom_feature(f32::from(tile_id.overscaled_z), Some(&feature))
609                    .with_global_state(global_state);
610                if !filter.evaluate(&context) {
611                    continue;
612                }
613            }
614
615            let converted = crate::tile::convert_feature(&feature, &geometry, &tile_id.canonical)?;
616            let mut converted = Feature::from(converted);
617            converted.source = render_layer.base().style.base().source.clone();
618            converted.source_layer = source_layer_id.clone();
619            converted.state = state.clone();
620            result.entry(layer_id.clone()).or_default().push(converted);
621        }
622        Ok(())
623    }
624
625    /// The bucket leaders and their layer ids (sorted, for inspection).
626    #[must_use]
627    pub(crate) fn bucket_layer_ids(&self) -> VecMap<String, Vec<String>> {
628        self.bucket_layer_ids.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()
629    }
630}
631
632/// `query_geometry`, a query's geometry in tile units, moved back by a
633/// layer's `translate` (in pixels, at `pixels_to_tile_units`), turned by
634/// `-bearing` for a translation anchored to the viewport: what a layer that
635/// translates its features tests them against. `None` without a
636/// translation.
637#[must_use]
638pub fn translate_query_geometry(
639    query_geometry: &GeometryCoordinates,
640    translate: [f32; 2],
641    anchor_type: TranslateAnchorType,
642    bearing: f32,
643    pixels_to_tile_units: f32,
644) -> Option<GeometryCoordinates> {
645    if translate[0] == 0.0 && translate[1] == 0.0 {
646        return None;
647    }
648
649    let mut translate_vec = GeometryCoordinate::new(
650        (translate[0] * pixels_to_tile_units) as i16,
651        (translate[1] * pixels_to_tile_units) as i16,
652    );
653    if anchor_type == TranslateAnchorType::Viewport {
654        translate_vec = crate::geo::math::rotate_i16(translate_vec, -bearing);
655    }
656
657    Some(
658        query_geometry
659            .iter()
660            .map(|p| GeometryCoordinate::new(p.x.wrapping_sub(translate_vec.x), p.y.wrapping_sub(translate_vec.y)))
661            .collect(),
662    )
663}
664
665/// A `FeatureIndex` as it crosses, for a tile worker in another wasm instance
666/// (`tile/worker_codec`): its entries and boxes, each string once, and not
667/// its tile data, which the side that gets the index has (it sent it).
668#[derive(mln_wire::Wire)]
669struct WireIndex {
670    strings: Vec<String>,
671    bucket_layer_ids: VecMap<String, Vec<String>>,
672    elements: Vec<WireEntry>,
673}
674
675/// An [`Entry`], with indices into `strings`, and its box.
676#[derive(mln_wire::Wire)]
677struct WireEntry {
678    index: usize,
679    sort_index: usize,
680    source_layer_name: u32,
681    bucket_leader_id: u32,
682    bounds: Bounds,
683}
684
685impl FeatureIndex {
686    fn to_wire(&self) -> WireIndex {
687        let mut strings: Vec<String> = Vec::new();
688        let mut string_ids: HashMap<*const u8, u32> = HashMap::default();
689        let mut intern = |s: &Arc<str>| -> u32 {
690            *string_ids.entry(s.as_ptr()).or_insert_with(|| {
691                strings.push(s.to_string());
692                (strings.len() - 1) as u32
693            })
694        };
695        let elements = self
696            .entries
697            .iter()
698            .zip(&self.boxes)
699            .map(|(entry, bounds)| WireEntry {
700                index: entry.index,
701                sort_index: entry.sort_index,
702                source_layer_name: intern(&entry.source_layer_name),
703                bucket_leader_id: intern(&entry.bucket_leader_id),
704                bounds: *bounds,
705            })
706            .collect();
707        WireIndex { strings, bucket_layer_ids: self.bucket_layer_ids(), elements }
708    }
709
710    /// The bucket leader of each box, in the order they were inserted.
711    #[cfg(test)]
712    pub(crate) fn leaders(&self) -> Vec<&str> {
713        self.entries.iter().map(|entry| &*entry.bucket_leader_id).collect()
714    }
715
716    /// The index as it crosses, without its tile data.
717    #[cfg(test)]
718    pub(crate) fn encode_grid(&self) -> Vec<u8> {
719        mln_wire::to_vec(&self.to_wire()).unwrap()
720    }
721}
722
723/// An index crosses without its tile data, which the side that reads it
724/// sets (`set_data`).
725impl mln_wire::Wire for FeatureIndex {
726    fn write(&self, w: &mut mln_wire::Writer) {
727        self.to_wire().write(w);
728    }
729
730    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
731        let parts = WireIndex::read(r)?;
732        let mut builder = FeatureIndexBuilder::new(None);
733        let strings: Vec<Arc<str>> = parts.strings.iter().map(|string| builder.intern_layer_name(string)).collect();
734        for (leader, layer_ids) in &parts.bucket_layer_ids {
735            builder.set_bucket_layer_ids(leader, layer_ids);
736        }
737        for element in parts.elements {
738            let (Some(source_layer_name), Some(bucket_leader_id)) =
739                (strings.get(element.source_layer_name as usize), strings.get(element.bucket_leader_id as usize))
740            else {
741                return r.fail("feature index string out of range");
742            };
743            // The leaders share the strings of `bucket_layer_ids`, as `insert`
744            // interns them.
745            let bucket_leader_id = builder.intern_leader_id(bucket_leader_id);
746            builder.entries.push(Entry {
747                index: element.index,
748                sort_index: element.sort_index,
749                source_layer_name: Arc::clone(source_layer_name),
750                bucket_leader_id,
751            });
752            builder.boxes.push(element.bounds);
753        }
754        Some(builder.finish())
755    }
756}
757
758#[cfg(test)]
759mod tests {
760    use geometry::Point;
761
762    use super::*;
763
764    #[test]
765    fn translate_query_geometry() {
766        let query: GeometryCoordinates = vec![Point::new(10, 10), Point::new(20, 20)];
767        assert_eq!(super::translate_query_geometry(&query, [0.0, 0.0], TranslateAnchorType::Map, 0.0, 8.0), None);
768        assert_eq!(
769            super::translate_query_geometry(&query, [1.0, -2.0], TranslateAnchorType::Map, 1.0, 8.0),
770            Some(vec![Point::new(2, 26), Point::new(12, 36)])
771        );
772        // Viewport anchor: the translation is rotated by -bearing.
773        assert_eq!(
774            super::translate_query_geometry(
775                &query,
776                [1.0, 0.0],
777                TranslateAnchorType::Viewport,
778                std::f32::consts::FRAC_PI_2,
779                8.0
780            ),
781            Some(vec![Point::new(10, 18), Point::new(20, 28)])
782        );
783    }
784
785    #[test]
786    fn insert_records_leaders_and_skips_rings_outside_the_tile() {
787        let mut builder = FeatureIndexBuilder::new(None);
788        builder.set_bucket_layer_ids("a", &["a".to_owned(), "b".to_owned()]);
789        let inside = GeometryCollection::from(vec![vec![Point::new(10, 10)]]);
790        let outside = GeometryCollection::from(vec![vec![Point::new(9000, 10)]]);
791        builder.insert(&inside, 0, "layer", "a");
792        builder.insert(&outside, 1, "layer", "a");
793        let index = builder.finish();
794        assert_eq!(index.bucket_layer_ids()["a"], vec!["a".to_owned(), "b".to_owned()]);
795        assert_eq!(index.leaders(), ["a"]);
796    }
797
798    #[test]
799    fn crosses_with_its_boxes() {
800        let mut builder = FeatureIndexBuilder::new(None);
801        builder.set_bucket_layer_ids("leader", &["leader".to_owned()]);
802        for i in 0..100 {
803            let x = (i * 80) as i16;
804            let ring = vec![Point::new(x, 10), Point::new(x + 5, 4000)];
805            builder.insert(&GeometryCollection::from(vec![ring.clone(), ring]), i, "layer", "leader");
806        }
807        let index = builder.finish();
808        let encoded = index.encode_grid();
809        let decoded: FeatureIndex = mln_wire::from_slice(&mln_wire::to_vec(&index).unwrap()).unwrap();
810        assert_eq!(decoded.entries, index.entries);
811        assert_eq!(decoded.boxes, index.boxes);
812        assert_eq!(decoded.encode_grid(), encoded);
813        assert_eq!(index.boxes[14], [560, 10, 565, 4000]);
814    }
815
816    #[test]
817    fn the_tile_holding_a_geometry_is_the_deepest_down_to_zoom_13() {
818        let point = |lon: f64, lat: f64| geo_types::Geometry::Point(geo_types::Point::new(lon, lat));
819        // A point a little east and north of 0, 0 is in the zoom-13 tile
820        // southeast of the center.
821        assert_eq!(tile_holding(&point(0.01, 0.01)), CanonicalTileID::new(13, 4096, 4095));
822        // A line across the prime meridian holds only in the world's tile,
823        // and one in the northwest quarter in that quarter's.
824        let line =
825            |a: (f64, f64), b: (f64, f64)| geo_types::Geometry::LineString(geo_types::LineString::from(vec![a, b]));
826        assert_eq!(tile_holding(&line((-1.0, 1.0), (1.0, 1.0))), CanonicalTileID::new(0, 0, 0));
827        assert_eq!(tile_holding(&line((-170.0, 80.0), (-100.0, 10.0))), CanonicalTileID::new(1, 0, 0));
828        // Past the Mercator world, near a pole or a world copy away, only the
829        // world's tile holds the coordinates.
830        assert_eq!(tile_holding(&point(0.0, 86.0)), CanonicalTileID::new(0, 0, 0));
831        assert_eq!(tile_holding(&point(190.0, 10.0)), CanonicalTileID::new(0, 0, 0));
832        // An empty geometry is placed in the world's tile.
833        let empty = geo_types::Geometry::MultiPoint(geo_types::MultiPoint::new(Vec::new()));
834        assert_eq!(tile_holding(&empty), CanonicalTileID::new(0, 0, 0));
835    }
836
837    #[test]
838    fn indexes_boxes_whose_extent_or_center_overflows_i16() {
839        // Wider than i16 holds, and with an x sum past it.
840        for (min_x, max_x) in [(-2000, 31000), (2000, 31000)] {
841            let boxes: Vec<Bounds> = (0..20).map(|i| [min_x, i * 10, max_x, i * 10 + 5]).collect();
842            let tree = build_tree(&boxes).expect("boxes");
843            assert_eq!(tree.search(3000, 0, 3010, 10).len(), 2);
844        }
845    }
846}