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 glam::Vec2;
14use mln_style::collections::VecMap;
15use mln_style::constants;
16use mln_style::crs::WorldMapping;
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::geometry::Point;
25use mln_style::hash::HashMap;
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    InPlace,
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::InPlace } 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, Copy, Debug, PartialEq, mln_wire::Wire)]
342struct Entry {
343    /// The feature's index in its source layer.
344    index: u32,
345    /// The order the feature was inserted in; a query returns later features
346    /// first.
347    sort_index: u32,
348    /// The feature's [`Origin`], by its index in the feature index's.
349    origin: u32,
350}
351
352/// The source layer of features, and the leader of the bucket they are in.
353#[derive(Clone, Debug, PartialEq, mln_wire::Wire)]
354struct Origin {
355    source_layer_name: String,
356    bucket_leader_id: String,
357}
358
359/// A box's min x, min y, max x and max y, in tile units.
360type Bounds = [i16; 4];
361
362/// A feature index as a tile's layout fills it.
363pub(crate) struct FeatureIndexBuilder {
364    /// The rings' entries and boxes, in insertion order.
365    entries: Vec<Entry>,
366    boxes: Vec<Bounds>,
367    origins: Vec<Origin>,
368    sort_index: u32,
369    bucket_layer_ids: HashMap<String, Vec<String>>,
370    tile_data: Option<TileData>,
371}
372
373impl FeatureIndexBuilder {
374    /// An empty index of `tile_data`'s features, sharing the tile data.
375    #[must_use]
376    pub(crate) fn new(tile_data: Option<TileData>) -> Self {
377        FeatureIndexBuilder {
378            entries: Vec::new(),
379            boxes: Vec::new(),
380            origins: Vec::new(),
381            sort_index: 0,
382            bucket_layer_ids: HashMap::default(),
383            tile_data,
384        }
385    }
386
387    /// Records the layers of the bucket whose leader is `bucket_leader_id`,
388    /// which a query of the bucket's features looks at.
389    pub(crate) fn set_bucket_layer_ids(&mut self, bucket_leader_id: &str, layer_ids: &[String]) {
390        self.bucket_layer_ids.insert(bucket_leader_id.to_owned(), layer_ids.to_vec());
391    }
392
393    /// The index of the origin of features of `source_layer_name` in the
394    /// bucket of `bucket_leader_id`, added if new.
395    fn origin(&mut self, source_layer_name: &str, bucket_leader_id: &str) -> u32 {
396        // A layout inserts a bucket's features together, so the origin is
397        // most often the last one.
398        let found = self.origins.iter().rposition(|origin| {
399            origin.source_layer_name == source_layer_name && origin.bucket_leader_id == bucket_leader_id
400        });
401        let index = found.unwrap_or_else(|| {
402            self.origins.push(Origin {
403                source_layer_name: source_layer_name.to_owned(),
404                bucket_leader_id: bucket_leader_id.to_owned(),
405            });
406            self.origins.len() - 1
407        });
408        index as u32
409    }
410
411    /// Adds the feature at `index` of `source_layer_name`, with the box of
412    /// each of its rings that reaches into the tile, to the bucket of
413    /// `bucket_leader_id`, whose layers [`set_bucket_layer_ids`](Self::set_bucket_layer_ids)
414    /// recorded.
415    pub(crate) fn insert(
416        &mut self,
417        geometries: &GeometryCollection,
418        index: usize,
419        source_layer_name: &str,
420        bucket_leader_id: &str,
421    ) {
422        // No source layer holds more features than a u32 counts.
423        let Ok(index) = u32::try_from(index) else {
424            return;
425        };
426        let origin = self.origin(source_layer_name, bucket_leader_id);
427        let sort_index = self.sort_index;
428        self.sort_index += 1;
429        for ring in geometries.iter() {
430            let Some((min, max)) = envelope(ring.iter().copied()) else {
431                continue;
432            };
433            let extent = constants::EXTENT;
434            if i32::from(min.x) < extent && i32::from(min.y) < extent && max.x >= 0 && max.y >= 0 {
435                self.entries.push(Entry { index, sort_index, origin });
436                self.boxes.push([min.x, min.y, max.x, max.y]);
437            }
438        }
439    }
440
441    /// The index of the features inserted.
442    #[must_use]
443    pub(crate) fn finish(self) -> FeatureIndex {
444        FeatureIndex {
445            tree: OnceLock::new(),
446            entries: self.entries,
447            boxes: self.boxes,
448            origins: self.origins,
449            bucket_layer_ids: self.bucket_layer_ids,
450            tile_data: self.tile_data,
451        }
452    }
453}
454
455/// An R-tree of `boxes`, whose items are their indices; `None` if there are
456/// none. It holds the coordinates as `i32`, as sorting sums them.
457fn build_tree(boxes: &[Bounds]) -> Option<RTree<i32>> {
458    if boxes.is_empty() {
459        return None;
460    }
461    let mut builder = RTreeBuilder::new(boxes.len() as u32);
462    for &bounds in boxes {
463        let [min_x, min_y, max_x, max_y] = bounds.map(i32::from);
464        builder.add(min_x, min_y, max_x, max_y);
465    }
466    Some(builder.finish::<HilbertSort>())
467}
468
469/// A tile's features by their bounding boxes, and the tile data they are in.
470pub struct FeatureIndex {
471    /// Indexes `boxes`, once a query has built it; `None` when there are
472    /// none.
473    tree: OnceLock<Option<RTree<i32>>>,
474    /// The rings' entries and boxes, in insertion order.
475    entries: Vec<Entry>,
476    boxes: Vec<Bounds>,
477    origins: Vec<Origin>,
478    bucket_layer_ids: HashMap<String, Vec<String>>,
479    tile_data: Option<TileData>,
480}
481
482impl std::fmt::Debug for FeatureIndex {
483    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
484        f.debug_struct("FeatureIndex")
485            .field("entries", &self.entries.len())
486            .field("bucket_layer_ids", &self.bucket_layer_ids)
487            .finish_non_exhaustive()
488    }
489}
490
491/// The bounding box (min, max) of int16 points; `None` if there are none.
492fn envelope(points: impl IntoIterator<Item = GeometryCoordinate>) -> Option<(GeometryCoordinate, GeometryCoordinate)> {
493    let mut iter = points.into_iter();
494    let first = iter.next()?;
495    let (mut min, mut max) = (first, first);
496    for p in iter {
497        min.x = min.x.min(p.x);
498        min.y = min.y.min(p.y);
499        max.x = max.x.max(p.x);
500        max.y = max.y.max(p.y);
501    }
502    Some((min, max))
503}
504
505impl FeatureIndex {
506    #[must_use]
507    pub(crate) fn data(&self) -> Option<&TileData> {
508        self.tile_data.as_ref()
509    }
510
511    /// Sets the tile data the index's features are in.
512    pub(crate) fn set_data(&mut self, tile_data: Option<TileData>) {
513        self.tile_data = tile_data;
514    }
515
516    /// Adds the features of `selection` that `region` touches to `result`,
517    /// later features first.
518    pub(crate) fn query(
519        &self,
520        result: &mut QueryResults,
521        selection: &FeatureSelection<'_>,
522        region: &QueryRegion<'_>,
523    ) -> Result<(), Error> {
524        if self.tile_data.is_none() {
525            return Ok(());
526        }
527        let Some(tree) = self.tree.get_or_init(|| build_tree(&self.boxes)) else {
528            return Ok(());
529        };
530
531        let globe_scale = map_aligned_padding_scale(region.view, region.projector.tile_id()) as f32;
532        let additional_padding =
533            (region.padding * region.pixels_to_tile_units * globe_scale).min(constants::EXTENT as f32) as i16;
534        let whole_tile = || {
535            let extent = constants::EXTENT as i16;
536            (GeometryCoordinate::new(0, 0), GeometryCoordinate::new(extent, extent))
537        };
538        let candidates = if region.whole_tile { Some(whole_tile()) } else { envelope(region.geometry.iter().copied()) };
539        let Some((min, max)) = candidates else {
540            return Ok(());
541        };
542        // The padded box's corners are tile coordinates, clamped to i16 as the
543        // query's are.
544        let (min_x, min_y) = (min.x.saturating_sub(additional_padding), min.y.saturating_sub(additional_padding));
545        let (max_x, max_y) = (max.x.saturating_add(additional_padding), max.y.saturating_add(additional_padding));
546        // Only a box that reaches into the tile finds features.
547        let extent = constants::EXTENT;
548        if min_x > max_x
549            || min_y > max_y
550            || max_x < 0
551            || max_y < 0
552            || i32::from(min_x) >= extent
553            || i32::from(min_y) >= extent
554        {
555            return Ok(());
556        }
557        let mut features: Vec<&Entry> = tree
558            .search(i32::from(min_x), i32::from(min_y), i32::from(max_x), i32::from(max_y))
559            .into_iter()
560            .filter_map(|i| self.entries.get(i as usize))
561            .collect();
562        // Later features first, each once.
563        features.sort_unstable_by_key(|feature| Reverse(feature.sort_index));
564        features.dedup_by_key(|feature| feature.sort_index);
565        for feature in features {
566            let origin = &self.origins[feature.origin as usize];
567            let entry = (feature.index as usize, &*origin.source_layer_name, &*origin.bucket_leader_id);
568            self.add_feature(result, entry, selection, Some(region))?;
569        }
570        Ok(())
571    }
572
573    /// The features of `symbol_features`, which the collision index found,
574    /// that `selection` selects, in the order their bucket last drew them.
575    pub(crate) fn lookup_symbol_features(
576        &self,
577        symbol_features: &[IndexedSubfeature],
578        selection: &FeatureSelection<'_>,
579        feature_sort_order: Option<&Arc<Vec<usize>>>,
580    ) -> Result<QueryResults, Error> {
581        let mut result = QueryResults::default();
582        if self.tile_data.is_none() {
583            return Ok(result);
584        }
585        let mut sorted_features: Vec<&IndexedSubfeature> = symbol_features.iter().collect();
586
587        // Later features first, as elsewhere. Symbols can move in their
588        // bucket's order after the collision index finds them, so a bucket
589        // that sorts its symbols by their place on screen gives its current
590        // order; the others keep the order of the source data. One feature
591        // needs no order.
592        if let Some(order) = feature_sort_order
593            && sorted_features.len() > 1
594        {
595            // A feature can have many symbols: it sorts by its first one, which
596            // a pass from the end of the order leaves.
597            let mut first: HashMap<usize, usize> = sorted_features.iter().map(|f| (f.index, order.len())).collect();
598            for (position, index) in order.iter().enumerate().rev() {
599                if let Some(slot) = first.get_mut(index) {
600                    *slot = position;
601                }
602            }
603            sorted_features.sort_by_key(|f| Reverse(first[&f.index]));
604        } else {
605            sorted_features.sort_by_key(|f| Reverse(f.sort_index));
606        }
607
608        for feature in sorted_features {
609            let entry = (feature.index, &*feature.source_layer_name, &*feature.bucket_leader_id);
610            self.add_feature(&mut result, entry, selection, None)?;
611        }
612        Ok(result)
613    }
614
615    /// Adds the feature `index` of the source layer `source_layer_name`,
616    /// of the bucket of `bucket_leader_id`, to `result` under each layer of
617    /// `selection` it is in, where it touches `region`. A symbol layer's
618    /// features need no region: the collision index found them.
619    fn add_feature(
620        &self,
621        result: &mut QueryResults,
622        (index, source_layer_name, bucket_leader_id): (usize, &str, &str),
623        selection: &FeatureSelection<'_>,
624        region: Option<&QueryRegion<'_>>,
625    ) -> Result<(), Error> {
626        let FeatureSelection { layers, options, global_state, tile_id, feature_state, world } = *selection;
627        let Some(tile_data) = &self.tile_data else {
628            return Ok(());
629        };
630        // Every leader the index holds has its bucket's layers.
631        let Some(layer_ids) = self.bucket_layer_ids.get(bucket_leader_id) else {
632            debug_assert!(false, "unknown bucket leader {bucket_leader_id}");
633            return Ok(());
634        };
635
636        // The source layer, the feature and its state are the same for every
637        // layer of the bucket: they are read once, where one of its layers
638        // is queried.
639        if !layer_ids.iter().any(|layer_id| layers.contains_key(layer_id)) {
640            return Ok(());
641        }
642        let Some(source_layer) = tile_data.layer(source_layer_name)? else {
643            debug_assert!(false, "source layer {source_layer_name} missing");
644            return Ok(());
645        };
646        let feature = source_layer.feature(index)?;
647        let geometry = feature.geometry()?;
648        let source_layer_id = source_layer.name().to_owned();
649        let mut state = FeatureState::default();
650        if let Some(source_feature_state) = feature_state
651            && let Some(id_str) = feature_id_to_string(&feature.id())
652        {
653            state = source_feature_state.state(Some(&source_layer_id), &id_str);
654        }
655
656        for layer_id in layer_ids {
657            let Some(render_layer) = layers.get(layer_id) else {
658                continue;
659            };
660
661            let needs_cross_tile_index = render_layer.base().evaluated_properties.entry().places();
662            // we use the float camera zoom here, not the integer tile ID zoom,
663            // because for the query we take into account the actual rendered
664            // size of the geometry
665            let hit = match region {
666                _ if needs_cross_tile_index => Hit::InPlace,
667                Some(region) => render_layer.hit(region, &feature, &geometry, &state),
668                None => Hit::Miss,
669            };
670            let distance = match hit {
671                Hit::Miss => continue,
672                Hit::InPlace => None,
673                Hit::At(distance) => Some(distance),
674            };
675
676            // Match layer filters and source queries, including overzoomed tiles.
677            if let Some(filter) = &options.filter {
678                let context = EvaluationContext::with_zoom_feature(f64::from(tile_id.overscaled_z), Some(&feature))
679                    .with_global_state(global_state);
680                if !filter.evaluate(&context) {
681                    continue;
682                }
683            }
684
685            let converted = crate::tile::convert_feature(&feature, &geometry, &tile_id.canonical, world)?;
686            let mut converted = Feature::from(converted);
687            converted.source = render_layer.base().style.base().source.clone();
688            converted.source_layer = source_layer_id.clone();
689            converted.state = state.clone();
690            result.entry(layer_id.clone()).or_default().push(Found { feature: converted, distance });
691        }
692        Ok(())
693    }
694
695    /// The bucket leaders and their layer ids (sorted, for inspection).
696    #[must_use]
697    pub(crate) fn bucket_layer_ids(&self) -> VecMap<String, Vec<String>> {
698        self.bucket_layer_ids.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
699    }
700}
701
702/// `query_geometry`, a query's geometry in tile units, moved back by a
703/// layer's `translate` (in pixels, at `pixels_to_tile_units`), turned by
704/// `-bearing` for a translation anchored to the viewport: what a layer that
705/// translates its features tests them against. `None` without a
706/// translation.
707#[must_use]
708pub fn translate_query_geometry(
709    query_geometry: &GeometryCoordinates,
710    translate: [f32; 2],
711    anchor_type: TranslateAnchorType,
712    bearing: f32,
713    pixels_to_tile_units: f32,
714) -> Option<GeometryCoordinates> {
715    if translate[0] == 0.0 && translate[1] == 0.0 {
716        return None;
717    }
718
719    let mut translate_vec = GeometryCoordinate::new(
720        (translate[0] * pixels_to_tile_units) as i16,
721        (translate[1] * pixels_to_tile_units) as i16,
722    );
723    if anchor_type == TranslateAnchorType::Viewport {
724        translate_vec = crate::geo::math::rotate_i16(translate_vec, -bearing);
725    }
726
727    Some(
728        query_geometry
729            .iter()
730            .map(|p| GeometryCoordinate::new(p.x.wrapping_sub(translate_vec.x), p.y.wrapping_sub(translate_vec.y)))
731            .collect(),
732    )
733}
734
735impl FeatureIndex {
736    /// The bucket leader of each box, in the order they were inserted.
737    #[cfg(test)]
738    pub(crate) fn leaders(&self) -> Vec<&str> {
739        self.entries.iter().map(|entry| &*self.origins[entry.origin as usize].bucket_leader_id).collect()
740    }
741
742    /// The index as it crosses, without its tile data.
743    #[cfg(test)]
744    pub(crate) fn encode_grid(&self) -> Vec<u8> {
745        mln_wire::to_vec(self).unwrap()
746    }
747}
748
749/// An index crosses, for a tile worker in another wasm instance
750/// (`tile/worker_codec`), without its tile data, which the side that reads
751/// it has (it sent it) and sets (`set_data`).
752impl mln_wire::Wire for FeatureIndex {
753    fn write(&self, w: &mut mln_wire::Writer<'_>) {
754        self.origins.write(w);
755        self.bucket_layer_ids().write(w);
756        self.entries.write(w);
757        self.boxes.write(w);
758    }
759
760    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
761        let origins = Vec::<Origin>::read(r)?;
762        let bucket_layer_ids = VecMap::<String, Vec<String>>::read(r)?;
763        let entries = Vec::<Entry>::read(r)?;
764        let boxes = Vec::<Bounds>::read(r)?;
765        if entries.len() != boxes.len() {
766            return r.fail("feature index entries and boxes differ in number");
767        }
768        if entries.iter().any(|entry| entry.origin as usize >= origins.len()) {
769            return r.fail("feature index origin out of range");
770        }
771        let bucket_layer_ids: HashMap<String, Vec<String>> = bucket_layer_ids.into_iter().collect();
772        if origins.iter().any(|origin| !bucket_layer_ids.contains_key(&origin.bucket_leader_id)) {
773            return r.fail("feature index bucket leader unknown");
774        }
775        Some(FeatureIndex { tree: OnceLock::new(), entries, boxes, origins, bucket_layer_ids, tile_data: None })
776    }
777}
778
779#[cfg(test)]
780mod tests {
781
782    use super::*;
783
784    #[test]
785    fn a_translated_layer_queries_the_geometry_moved_against_its_translation() {
786        let query: GeometryCoordinates = vec![Point::new(10, 10), Point::new(20, 20)];
787        assert_eq!(translate_query_geometry(&query, [0.0, 0.0], TranslateAnchorType::Map, 0.0, 8.0), None);
788        assert_eq!(
789            translate_query_geometry(&query, [1.0, -2.0], TranslateAnchorType::Map, 1.0, 8.0),
790            Some(vec![Point::new(2, 26), Point::new(12, 36)])
791        );
792        // Viewport anchor: the translation is rotated by -bearing.
793        assert_eq!(
794            translate_query_geometry(
795                &query,
796                [1.0, 0.0],
797                TranslateAnchorType::Viewport,
798                std::f32::consts::FRAC_PI_2,
799                8.0
800            ),
801            Some(vec![Point::new(10, 18), Point::new(20, 28)])
802        );
803    }
804
805    /// A feature is indexed by the box of each of its rings that reaches
806    /// into the tile; a ring outside the tile or without points adds none.
807    #[test]
808    fn insert_indexes_the_rings_that_reach_into_the_tile() {
809        let mut builder = FeatureIndexBuilder::new(None);
810        builder.set_bucket_layer_ids("a", &["a".to_owned(), "b".to_owned()]);
811        let inside = vec![Point::new(10, 10), Point::new(20, 30)];
812        let outside = vec![Point::new(9000, 10)];
813        builder.insert(&GeometryCollection::from(vec![inside.clone()]), 0, "layer", "a");
814        builder.insert(&GeometryCollection::from(vec![outside]), 1, "layer", "a");
815        builder.insert(&GeometryCollection::from(vec![Vec::new()]), 2, "layer", "a");
816        builder.insert(&GeometryCollection::from(vec![Vec::new(), inside]), 3, "layer", "a");
817        let index = builder.finish();
818        assert_eq!(index.bucket_layer_ids()["a"], vec!["a".to_owned(), "b".to_owned()]);
819        assert_eq!(index.leaders(), ["a", "a"]);
820        assert_eq!(index.entries.iter().map(|entry| entry.index).collect::<Vec<_>>(), [0, 3]);
821        assert_eq!(index.boxes, [[10, 10, 20, 30], [10, 10, 20, 30]]);
822    }
823
824    #[test]
825    fn crosses_with_its_boxes() {
826        let mut builder = FeatureIndexBuilder::new(None);
827        builder.set_bucket_layer_ids("leader", &["leader".to_owned()]);
828        for i in 0..100 {
829            let x = (i * 80) as i16;
830            let ring = vec![Point::new(x, 10), Point::new(x + 5, 4000)];
831            builder.insert(&GeometryCollection::from(vec![ring.clone(), ring]), i, "layer", "leader");
832        }
833        let index = builder.finish();
834        let encoded = index.encode_grid();
835        let decoded: FeatureIndex = mln_wire::from_slice(&mln_wire::to_vec(&index).unwrap()).unwrap();
836        assert_eq!(decoded.entries, index.entries);
837        assert_eq!(decoded.boxes, index.boxes);
838        assert_eq!(decoded.encode_grid(), encoded);
839        assert_eq!(index.boxes[14], [560, 10, 565, 4000]);
840    }
841
842    #[test]
843    fn the_tile_holding_a_geometry_is_the_deepest_down_to_zoom_13() {
844        let point = |lon: f64, lat: f64| geo_types::Geometry::Point(geo_types::Point::new(lon, lat));
845        // A point a little east and north of 0, 0 is in the zoom-13 tile
846        // southeast of the center.
847        assert_eq!(tile_holding(&point(0.01, 0.01)), CanonicalTileID::new(13, 4096, 4095));
848        // A line across the prime meridian holds only in the world's tile,
849        // and one in the northwest quarter in that quarter's.
850        let line =
851            |a: (f64, f64), b: (f64, f64)| geo_types::Geometry::LineString(geo_types::LineString::from(vec![a, b]));
852        assert_eq!(tile_holding(&line((-1.0, 1.0), (1.0, 1.0))), CanonicalTileID::new(0, 0, 0));
853        assert_eq!(tile_holding(&line((-170.0, 80.0), (-100.0, 10.0))), CanonicalTileID::new(1, 0, 0));
854        // Past the Mercator world, near a pole or a world copy away, only the
855        // world's tile holds the coordinates.
856        assert_eq!(tile_holding(&point(0.0, 86.0)), CanonicalTileID::new(0, 0, 0));
857        assert_eq!(tile_holding(&point(190.0, 10.0)), CanonicalTileID::new(0, 0, 0));
858        // An empty geometry is placed in the world's tile.
859        let empty = geo_types::Geometry::MultiPoint(geo_types::MultiPoint::new(Vec::new()));
860        assert_eq!(tile_holding(&empty), CanonicalTileID::new(0, 0, 0));
861    }
862
863    #[test]
864    fn indexes_boxes_whose_extent_or_center_overflows_i16() {
865        // Wider than i16 holds, and with an x sum past it.
866        for (min_x, max_x) in [(-2000, 31000), (2000, 31000)] {
867            let boxes: Vec<Bounds> = (0..20).map(|i| [min_x, i * 10, max_x, i * 10 + 5]).collect();
868            let tree = build_tree(&boxes).expect("boxes");
869            assert_eq!(tree.search(3000, 0, 3010, 10).len(), 2);
870        }
871    }
872}