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