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