1use std::sync::Arc;
10
11use geo::{BooleanOps, BoundingRect, Buffer, Intersects};
12
13use crate::layers::Layer;
14use crate::source::input::{DataSource, InputFeature};
15use crate::tile::feature::PropValue;
16
17use super::buildings::ProcessedFeature;
18
19const MASK_MARGIN_DEG: f64 = 0.005;
23
24#[derive(Debug)]
32pub struct IndiaMask {
33 land: geo::MultiPolygon<f64>,
34 bounds: geo::Rect<f64>,
35}
36
37impl IndiaMask {
38 pub fn from_features(features: &[InputFeature]) -> Option<Self> {
42 let pieces: Vec<geo::Polygon<f64>> = features
43 .iter()
44 .flat_map(|f| closed_rings(&f.geometry))
45 .map(|ring| geo::Polygon::new(ring, vec![]))
46 .collect();
47 if pieces.is_empty() {
48 return None;
49 }
50 let land = geo::MultiPolygon::new(pieces).buffer(MASK_MARGIN_DEG);
51 let bounds = land.bounding_rect()?;
52 Some(Self { land, bounds })
53 }
54
55 pub fn clip(&self, feature: ProcessedFeature) -> Option<ProcessedFeature> {
59 if feature.layer != Layer::Boundaries || !is_country(&feature) {
60 return Some(feature);
61 }
62 let lines = match feature.geometry.as_ref() {
63 geo::Geometry::LineString(line) => geo::MultiLineString::new(vec![line.clone()]),
64 geo::Geometry::MultiLineString(lines) => lines.clone(),
65 _ => return Some(feature),
66 };
67 match lines.bounding_rect() {
68 Some(rect) if rect.intersects(&self.bounds) => {}
69 _ => return Some(feature),
70 }
71 let outside = self.land.clip(&lines, true);
72 if outside.0.is_empty() {
73 return None;
74 }
75 Some(ProcessedFeature {
76 geometry: Arc::new(geo::Geometry::MultiLineString(outside)),
77 ..feature
78 })
79 }
80}
81
82fn closed_rings(geometry: &geo::Geometry<f64>) -> Vec<geo::LineString<f64>> {
84 let is_ring = |line: &&geo::LineString<f64>| line.is_closed() && line.0.len() >= 4;
85 match geometry {
86 geo::Geometry::LineString(line) => [line].into_iter().filter(is_ring).cloned().collect(),
87 geo::Geometry::MultiLineString(lines) => lines.0.iter().filter(is_ring).cloned().collect(),
88 geo::Geometry::Polygon(polygon) => vec![polygon.exterior().clone()],
89 geo::Geometry::MultiPolygon(polygons) => {
90 polygons.0.iter().map(|p| p.exterior().clone()).collect()
91 }
92 _ => Vec::new(),
93 }
94}
95
96fn is_country(feature: &ProcessedFeature) -> bool {
98 feature
99 .properties
100 .iter()
101 .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
102}
103
104const INDIA_BBOX: [f64; 4] = [68.0, 6.5, 97.5, 37.2];
109
110pub fn process(feature: &InputFeature) -> Option<ProcessedFeature> {
114 match &feature.source {
115 DataSource::Overture { .. } => process_overture(feature),
116 DataSource::NaturalEarth { .. } => process_ne(feature),
117 DataSource::Osm { .. } => process_osm(feature),
118 DataSource::IndiaBoundary => process_india(feature),
119 _ => None,
120 }
121}
122
123fn process_overture(feature: &InputFeature) -> Option<ProcessedFeature> {
132 let (kind, admin_level, min_zoom) = overture_subtype_to_kind(feature.get_str("subtype")?)?;
133
134 let disputed = matches!(
135 feature.properties.get("is_disputed"),
136 Some(PropValue::Bool(true))
137 );
138
139 let sort_rank = if disputed { 288 } else { 289 };
140
141 let mut properties = Vec::with_capacity(4);
142 properties.push(("kind".into(), PropValue::Str(kind.into())));
143 properties.push(("kind_detail".into(), PropValue::I64(admin_level)));
144
145 if disputed {
146 properties.push(("disputed".into(), PropValue::Bool(true)));
147 }
148
149 Some(ProcessedFeature {
150 id: feature.id,
151 geometry: feature.geometry.clone(),
152 layer: Layer::Boundaries,
153 min_zoom,
154 max_zoom: 15,
155 sort_rank,
156 properties,
157 })
158}
159
160fn process_ne(feature: &InputFeature) -> Option<ProcessedFeature> {
164 let source_layer = feature.ne_source_layer()?;
165
166 let is_boundary_layer = source_layer.starts_with("ne_10m_admin_0_boundary")
167 || source_layer.starts_with("ne_10m_admin_1");
168
169 if !is_boundary_layer {
170 return None;
171 }
172
173 let featurecla = feature.get_str("featurecla").unwrap_or("");
174
175 let (kind, admin_level, disputed) = match featurecla {
176 "International boundary (verify)" => ("country", 2i64, false),
177 "Disputed (please verify)" => ("country", 2, true),
178 "Line of control (please verify)" => ("country", 2, true),
179 "Indefinite (please verify)" => ("country", 2, true),
180 "Lease limit" => ("country", 2, true),
181 "Overlay limit" => ("country", 2, true),
182 "Admin-1 boundary" => ("region", 4, false),
183 "Admin-1 statistical boundary" => ("region", 4, false),
184 "Admin-1 region boundary" => ("region", 4, false),
185 "Unrecognized" => ("country", 2, true),
186 _ if featurecla.contains("disputed") || featurecla.contains("Disputed") => {
187 ("country", 2, true)
188 }
189 _ if featurecla.contains("Admin-1") => ("region", 4, false),
190 _ => ("country", 2, false),
191 };
192
193 let sort_rank = if disputed { 288 } else { 289 };
194
195 let mut properties = Vec::with_capacity(4);
196 properties.push(("kind".into(), PropValue::Str(kind.into())));
197 properties.push(("kind_detail".into(), PropValue::I64(admin_level)));
198
199 if disputed {
200 properties.push(("disputed".into(), PropValue::Bool(true)));
201 }
202
203 let ne_min_zoom = feature
207 .get_f64("min_zoom")
208 .map(|v| (v as u8).min(5))
209 .or_else(|| feature.get_i64("min_zoom").map(|v| (v as u8).min(5)))
210 .unwrap_or(0);
211
212 Some(ProcessedFeature {
213 id: feature.id,
214 geometry: feature.geometry.clone(),
215 layer: Layer::Boundaries,
216 min_zoom: ne_min_zoom,
217 max_zoom: 5,
218 sort_rank,
219 properties,
220 })
221}
222
223fn process_osm(feature: &InputFeature) -> Option<ProcessedFeature> {
228 if !feature.can_be_line() {
229 return None;
230 }
231
232 let relations = feature.osm_relations();
233 if relations.is_empty() {
234 if feature.has_tag("boundary", "administrative") || feature.has_tag("boundary", "disputed")
236 {
237 let admin_level = feature
238 .get_str("admin_level")
239 .and_then(|v| v.parse::<i64>().ok())
240 .unwrap_or(2);
241
242 let disputed = feature.has_tag("boundary", "disputed")
243 || feature.get_str("disputed").is_some_and(|v| v == "yes")
244 || feature
245 .get_str("boundary")
246 .is_some_and(|v| v == "disputed" || v == "claim");
247
248 if admin_level == 2 && is_within_india_bbox(feature) && !disputed {
249 return None;
250 }
251
252 let (kind, min_zoom) = admin_level_to_kind(admin_level)?;
253 let sort_rank = if disputed { 288 } else { 289 };
254
255 let mut properties = Vec::with_capacity(4);
256 properties.push(("kind".into(), PropValue::Str(kind.into())));
257 properties.push(("kind_detail".into(), PropValue::I64(admin_level)));
258 if disputed {
259 properties.push(("disputed".into(), PropValue::Bool(true)));
260 }
261
262 return Some(ProcessedFeature {
263 id: feature.id,
264 geometry: feature.geometry.clone(),
265 layer: Layer::Boundaries,
266 min_zoom,
267 max_zoom: 15,
268 sort_rank,
269 properties,
270 });
271 }
272 return None;
273 }
274
275 let best_relation = relations
277 .iter()
278 .filter(|r| {
279 r.tags.get("type").is_some_and(|t| t == "boundary")
280 || r.tags
281 .get("boundary")
282 .is_some_and(|b| b == "administrative" || b == "disputed")
283 })
284 .min_by_key(|r| r.admin_level.unwrap_or(99));
285
286 let rel = best_relation?;
287 let admin_level = i64::from(rel.admin_level.unwrap_or(2));
288
289 let disputed = rel.disputed
290 || rel
291 .tags
292 .get("boundary")
293 .is_some_and(|v| v == "disputed" || v == "claim")
294 || rel.tags.get("disputed").is_some_and(|v| v == "yes");
295
296 if admin_level == 2 && is_within_india_bbox(feature) && !disputed {
298 return None;
299 }
300
301 let (kind, min_zoom) = admin_level_to_kind(admin_level)?;
302 let sort_rank = if disputed { 288 } else { 289 };
303
304 let mut properties = Vec::with_capacity(5);
305 properties.push(("kind".into(), PropValue::Str(kind.into())));
306 properties.push(("kind_detail".into(), PropValue::I64(admin_level)));
307
308 if disputed {
309 properties.push(("disputed".into(), PropValue::Bool(true)));
310 }
311
312 if let Some(disputed_by) = feature.get_str("disputed_by") {
313 properties.push((
314 "disputed_by".into(),
315 PropValue::Str(disputed_by.to_string()),
316 ));
317 }
318 if let Some(claimed_by) = feature.get_str("claimed_by") {
319 properties.push(("claimed_by".into(), PropValue::Str(claimed_by.to_string())));
320 }
321
322 Some(ProcessedFeature {
323 id: feature.id,
324 geometry: feature.geometry.clone(),
325 layer: Layer::Boundaries,
326 min_zoom,
327 max_zoom: 15,
328 sort_rank,
329 properties,
330 })
331}
332
333fn process_india(feature: &InputFeature) -> Option<ProcessedFeature> {
337 let kind = feature.get_str("kind").unwrap_or("country");
338 let kind_detail = feature.get_i64("kind_detail").unwrap_or(2);
339
340 let mut properties = Vec::with_capacity(3);
341 properties.push(("kind".into(), PropValue::Str(kind.to_string())));
342 properties.push(("kind_detail".into(), PropValue::I64(kind_detail)));
343
344 if let Some(name) = feature.get_str("name") {
345 properties.push(("name".into(), PropValue::Str(name.to_string())));
346 }
347
348 Some(ProcessedFeature {
349 id: feature.id,
350 geometry: feature.geometry.clone(),
351 layer: Layer::Boundaries,
352 min_zoom: 0,
353 max_zoom: 15,
354 sort_rank: 289,
355 properties,
356 })
357}
358
359fn overture_subtype_to_kind(subtype: &str) -> Option<(&'static str, i64, u8)> {
365 match subtype {
366 "country" | "dependency" => Some(("country", 2, 6)),
367 "macroregion" | "region" => Some(("region", 4, 6)),
368 "macrocounty" | "county" => Some(("county", 6, 8)),
369 "localadmin" | "locality" | "borough" => Some(("locality", 8, 10)),
370 _ => None,
371 }
372}
373
374const fn admin_level_to_kind(admin_level: i64) -> Option<(&'static str, u8)> {
379 match admin_level {
380 2 => Some(("country", 6)),
381 3 | 4 => Some(("region", 6)),
382 5 | 6 => Some(("county", 8)),
383 7 | 8 => Some(("locality", 10)),
384 _ => None,
385 }
386}
387
388fn is_within_india_bbox(feature: &InputFeature) -> bool {
390 if let Some(bbox) = feature.bbox {
391 let cx = (bbox[0] + bbox[2]) / 2.0;
392 let cy = (bbox[1] + bbox[3]) / 2.0;
393 return (INDIA_BBOX[0]..=INDIA_BBOX[2]).contains(&cx)
394 && (INDIA_BBOX[1]..=INDIA_BBOX[3]).contains(&cy);
395 }
396
397 match feature.geometry.as_ref() {
399 geo::Geometry::LineString(ls) => {
400 if let Some(coord) = ls.0.first() {
401 return coord.x >= INDIA_BBOX[0]
402 && coord.x <= INDIA_BBOX[2]
403 && coord.y >= INDIA_BBOX[1]
404 && coord.y <= INDIA_BBOX[3];
405 }
406 }
407 geo::Geometry::Point(pt) => {
408 return pt.x() >= INDIA_BBOX[0]
409 && pt.x() <= INDIA_BBOX[2]
410 && pt.y() >= INDIA_BBOX[1]
411 && pt.y() <= INDIA_BBOX[3];
412 }
413 _ => {}
414 }
415 false
416}
417
418#[cfg(test)]
419mod tests {
420 use super::*;
421 use crate::source::input::{DataSource, OsmElementType, RelationInfo};
422 use std::collections::HashMap;
423 use std::sync::Arc;
424
425 fn props_map(props: &[(&str, PropValue)]) -> HashMap<String, PropValue> {
426 let mut m = HashMap::new();
427 for (k, v) in props {
428 m.insert(k.to_string(), v.clone());
429 }
430 m
431 }
432
433 fn line_geom() -> Arc<geo::Geometry<f64>> {
434 Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
435 (0.0, 0.0),
436 (1.0, 1.0),
437 ])))
438 }
439
440 fn make_feature(props: &[(&str, PropValue)]) -> InputFeature {
441 InputFeature {
442 id: 1,
443 geometry: line_geom(),
444 properties: props_map(props),
445 bbox: None,
446 source: DataSource::Overture {
447 theme: String::new(),
448 otype: String::new(),
449 },
450 }
451 }
452
453 fn make_ne_feature(layer: &str, props: &[(&str, PropValue)]) -> InputFeature {
454 InputFeature {
455 id: 1,
456 geometry: line_geom(),
457 properties: props_map(props),
458 bbox: None,
459 source: DataSource::NaturalEarth {
460 source_layer: layer.to_string(),
461 },
462 }
463 }
464
465 fn make_osm_way(props: &[(&str, PropValue)], relations: Vec<RelationInfo>) -> InputFeature {
466 InputFeature {
467 id: 1,
468 geometry: line_geom(),
469 properties: props_map(props),
470 bbox: None,
471 source: DataSource::Osm {
472 element_type: OsmElementType::Way,
473 relations,
474 },
475 }
476 }
477
478 fn make_india_feature(props: &[(&str, PropValue)]) -> InputFeature {
479 InputFeature {
480 id: 1,
481 geometry: line_geom(),
482 properties: props_map(props),
483 bbox: None,
484 source: DataSource::IndiaBoundary,
485 }
486 }
487
488 fn rel_with(admin_level: Option<i32>, disputed: bool, tags: &[(&str, &str)]) -> RelationInfo {
489 let mut t = HashMap::new();
490 for (k, v) in tags {
491 t.insert(k.to_string(), v.to_string());
492 }
493 RelationInfo {
494 id: 1,
495 admin_level,
496 disputed,
497 role: String::new(),
498 tags: t,
499 }
500 }
501
502 #[test]
505 fn dispatch_unsupported_source_returns_none() {
506 let feat = InputFeature {
507 id: 1,
508 geometry: line_geom(),
509 properties: HashMap::new(),
510 bbox: None,
511 source: DataSource::LandPolygons,
512 };
513 assert!(process(&feat).is_none());
514
515 let feat2 = InputFeature {
516 source: DataSource::WaterPolygons,
517 ..feat
518 };
519 assert!(process(&feat2).is_none());
520 }
521
522 fn kind_of(result: &ProcessedFeature) -> Option<&PropValue> {
525 result
526 .properties
527 .iter()
528 .find(|(k, _)| k == "kind")
529 .map(|(_, v)| v)
530 }
531
532 fn detail_of(result: &ProcessedFeature) -> Option<&PropValue> {
533 result
534 .properties
535 .iter()
536 .find(|(k, _)| k == "kind_detail")
537 .map(|(_, v)| v)
538 }
539
540 #[test]
543 fn overture_county_with_relative_admin_level_2_is_not_a_country() {
544 let feat = make_feature(&[
545 ("subtype", PropValue::Str("county".into())),
546 ("admin_level", PropValue::I64(2)),
547 ]);
548 let result = process(&feat).unwrap();
549 assert_eq!(kind_of(&result), Some(&PropValue::Str("county".into())));
550 assert_eq!(detail_of(&result), Some(&PropValue::I64(6)));
551 assert_eq!(result.min_zoom, 8);
552 }
553
554 #[test]
557 fn overture_country_with_relative_admin_level_1_is_kept() {
558 let feat = make_feature(&[
559 ("subtype", PropValue::Str("country".into())),
560 ("admin_level", PropValue::I64(1)),
561 ]);
562 let result = process(&feat).unwrap();
563 assert_eq!(result.layer, Layer::Boundaries);
564 assert_eq!(kind_of(&result), Some(&PropValue::Str("country".into())));
565 assert_eq!(detail_of(&result), Some(&PropValue::I64(2)));
566 assert_eq!(result.min_zoom, 6);
567 assert_eq!(result.sort_rank, 289);
568 }
569
570 #[test]
571 fn overture_region_with_relative_admin_level_1_is_kept() {
572 let feat = make_feature(&[
573 ("subtype", PropValue::Str("region".into())),
574 ("admin_level", PropValue::I64(1)),
575 ]);
576 let result = process(&feat).unwrap();
577 assert_eq!(kind_of(&result), Some(&PropValue::Str("region".into())));
578 assert_eq!(detail_of(&result), Some(&PropValue::I64(4)));
579 }
580
581 #[test]
582 fn overture_subtype_levels_follow_the_osm_scale() {
583 let cases = [
584 ("dependency", "country", 2, 6),
585 ("macroregion", "region", 4, 6),
586 ("macrocounty", "county", 6, 8),
587 ("localadmin", "locality", 8, 10),
588 ("locality", "locality", 8, 10),
589 ("borough", "locality", 8, 10),
590 ];
591 for (subtype, kind, level, zoom) in cases {
592 let feat = make_feature(&[("subtype", PropValue::Str(subtype.into()))]);
593 let result = process(&feat).unwrap();
594 assert_eq!(
595 kind_of(&result),
596 Some(&PropValue::Str(kind.into())),
597 "{subtype}"
598 );
599 assert_eq!(
600 detail_of(&result),
601 Some(&PropValue::I64(level)),
602 "{subtype}"
603 );
604 assert_eq!(result.min_zoom, zoom, "{subtype}");
605 }
606 }
607
608 #[test]
609 fn overture_neighborhood_boundaries_are_dropped() {
610 for subtype in ["macrohood", "neighborhood", "microhood"] {
611 let feat = make_feature(&[("subtype", PropValue::Str(subtype.into()))]);
612 assert!(process(&feat).is_none(), "{subtype}");
613 }
614 }
615
616 #[test]
617 fn overture_boundary_without_subtype_is_dropped() {
618 let feat = make_feature(&[("admin_level", PropValue::I64(2))]);
619 assert!(process(&feat).is_none());
620 }
621
622 #[test]
624 fn overture_disputed_boolean_lowers_sort_rank() {
625 let feat = make_feature(&[
626 ("subtype", PropValue::Str("country".into())),
627 ("is_disputed", PropValue::Bool(true)),
628 ]);
629 let result = process(&feat).unwrap();
630 assert_eq!(result.sort_rank, 288);
631 assert!(
632 result
633 .properties
634 .iter()
635 .any(|(k, v)| k == "disputed" && *v == PropValue::Bool(true))
636 );
637 }
638
639 #[test]
640 fn overture_undisputed_boolean_keeps_default_sort_rank() {
641 let feat = make_feature(&[
642 ("subtype", PropValue::Str("country".into())),
643 ("is_disputed", PropValue::Bool(false)),
644 ]);
645 let result = process(&feat).unwrap();
646 assert_eq!(result.sort_rank, 289);
647 assert!(!result.properties.iter().any(|(k, _)| k == "disputed"));
648 }
649 #[test]
652 fn ne_non_boundary_layer_returns_none() {
653 let feat = make_ne_feature("ne_10m_lakes", &[]);
654 assert!(process(&feat).is_none());
655 }
656
657 #[test]
662 fn ne_featurecla_values_map_to_kind_level_and_disputed() {
663 let cases = [
664 ("Disputed (please verify)", "country", 2, true, 288),
665 ("Line of control (please verify)", "country", 2, true, 288),
666 ("Indefinite (please verify)", "country", 2, true, 288),
667 ("Lease limit", "country", 2, true, 288),
668 ("Overlay limit", "country", 2, true, 288),
669 ("Unrecognized", "country", 2, true, 288),
670 ("Some weird disputed thing", "country", 2, true, 288),
671 ("Something Disputed weird", "country", 2, true, 288),
672 ("Admin-1 boundary", "region", 4, false, 289),
673 ("Admin-1 statistical boundary", "region", 4, false, 289),
674 ("Admin-1 region boundary", "region", 4, false, 289),
675 ("Custom Admin-1 thing", "region", 4, false, 289),
676 ];
677 for (featurecla, kind, level, disputed, rank) in cases {
678 let feat = make_ne_feature(
679 "ne_10m_admin_0_boundary_lines_land",
680 &[("featurecla", PropValue::Str(featurecla.into()))],
681 );
682 let result = process(&feat).expect(featurecla);
683 let prop = |key: &str| {
684 result
685 .properties
686 .iter()
687 .find(|(k, _)| k == key)
688 .map(|(_, v)| v.clone())
689 };
690 assert_eq!(
691 prop("kind"),
692 Some(PropValue::Str(kind.into())),
693 "{featurecla}"
694 );
695 assert_eq!(
696 prop("kind_detail"),
697 Some(PropValue::I64(level)),
698 "{featurecla}"
699 );
700 assert_eq!(
701 prop("disputed"),
702 disputed.then_some(PropValue::Bool(true)),
703 "{featurecla}"
704 );
705 assert_eq!(result.sort_rank, rank, "{featurecla}");
706 }
707 }
708
709 #[test]
710 fn ne_admin_0_international_boundary() {
711 let feat = make_ne_feature(
712 "ne_10m_admin_0_boundary_lines_land",
713 &[(
714 "featurecla",
715 PropValue::Str("International boundary (verify)".into()),
716 )],
717 );
718 let result = process(&feat).unwrap();
719 assert_eq!(result.layer, Layer::Boundaries);
720 assert_eq!(result.max_zoom, 5);
721 assert_eq!(result.sort_rank, 289);
722 assert!(
723 result
724 .properties
725 .iter()
726 .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
727 );
728 }
729
730 #[test]
731 fn ne_unknown_default_country() {
732 let feat = make_ne_feature(
733 "ne_10m_admin_0_boundary_lines_land",
734 &[("featurecla", PropValue::Str("Mystery line".into()))],
735 );
736 let result = process(&feat).unwrap();
737 assert!(
738 result
739 .properties
740 .iter()
741 .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
742 );
743 assert_eq!(result.sort_rank, 289);
744 }
745
746 #[test]
747 fn ne_missing_featurecla_default_country() {
748 let feat = make_ne_feature("ne_10m_admin_0_boundary_lines_land", &[]);
749 let result = process(&feat).unwrap();
750 assert!(
751 result
752 .properties
753 .iter()
754 .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
755 );
756 }
757
758 #[test]
759 fn ne_min_zoom_from_f64_clamped() {
760 let feat = make_ne_feature(
761 "ne_10m_admin_0_boundary_lines_land",
762 &[
763 ("featurecla", PropValue::Str("Mystery".into())),
764 ("min_zoom", PropValue::F64(8.0)),
765 ],
766 );
767 let result = process(&feat).unwrap();
768 assert_eq!(result.min_zoom, 5);
769 }
770
771 #[test]
772 fn ne_min_zoom_from_f64_within_range() {
773 let feat = make_ne_feature(
774 "ne_10m_admin_0_boundary_lines_land",
775 &[
776 ("featurecla", PropValue::Str("Mystery".into())),
777 ("min_zoom", PropValue::F64(3.0)),
778 ],
779 );
780 let result = process(&feat).unwrap();
781 assert_eq!(result.min_zoom, 3);
782 }
783
784 #[test]
785 fn ne_min_zoom_from_i64() {
786 let feat = make_ne_feature(
787 "ne_10m_admin_0_boundary_lines_land",
788 &[
789 ("featurecla", PropValue::Str("Mystery".into())),
790 ("min_zoom", PropValue::I64(2)),
791 ],
792 );
793 let result = process(&feat).unwrap();
794 assert_eq!(result.min_zoom, 2);
795 }
796
797 #[test]
798 fn ne_min_zoom_default_zero() {
799 let feat = make_ne_feature(
800 "ne_10m_admin_0_boundary_lines_land",
801 &[("featurecla", PropValue::Str("Mystery".into()))],
802 );
803 let result = process(&feat).unwrap();
804 assert_eq!(result.min_zoom, 0);
805 }
806
807 #[test]
810 fn osm_non_line_returns_none() {
811 let feat = InputFeature {
812 id: 1,
813 geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
814 properties: HashMap::new(),
815 bbox: None,
816 source: DataSource::Osm {
817 element_type: OsmElementType::Way,
818 relations: vec![],
819 },
820 };
821 assert!(process(&feat).is_none());
822 }
823
824 #[test]
825 fn osm_no_relations_no_tag_returns_none() {
826 let feat = make_osm_way(&[], vec![]);
827 assert!(process(&feat).is_none());
828 }
829
830 #[test]
831 fn osm_no_relations_with_admin_tag() {
832 let feat = make_osm_way(
833 &[
834 ("boundary", PropValue::Str("administrative".into())),
835 ("admin_level", PropValue::Str("4".into())),
836 ],
837 vec![],
838 );
839 let result = process(&feat).unwrap();
840 assert_eq!(result.min_zoom, 6);
841 assert!(
842 result
843 .properties
844 .iter()
845 .any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
846 );
847 }
848
849 #[test]
852 fn osm_no_relations_missing_or_unparseable_admin_level_is_a_country() {
853 let missing = vec![("boundary", PropValue::Str("administrative".into()))];
854 let mut unparseable = missing.clone();
855 unparseable.push(("admin_level", PropValue::Str("not-a-number".into())));
856 for tags in [missing, unparseable] {
857 let result = process(&make_osm_way(&tags, vec![])).expect("a boundary");
858 assert_eq!(
859 kind_of(&result),
860 Some(&PropValue::Str("country".into())),
861 "{tags:?}"
862 );
863 }
864 }
865
866 #[test]
867 fn osm_no_relations_dropped_admin_level_returns_none() {
868 let feat = make_osm_way(
869 &[
870 ("boundary", PropValue::Str("administrative".into())),
871 ("admin_level", PropValue::Str("9".into())),
872 ],
873 vec![],
874 );
875 assert!(process(&feat).is_none());
876 }
877
878 #[test]
879 fn osm_no_relations_boundary_disputed_tag() {
880 let feat = make_osm_way(&[("boundary", PropValue::Str("disputed".into()))], vec![]);
881 let result = process(&feat).unwrap();
882 assert_eq!(result.sort_rank, 288);
883 assert!(
884 result
885 .properties
886 .iter()
887 .any(|(k, v)| k == "disputed" && *v == PropValue::Bool(true))
888 );
889 }
890
891 #[test]
892 fn osm_no_relations_disputed_yes_tag() {
893 let feat = make_osm_way(
894 &[
895 ("boundary", PropValue::Str("administrative".into())),
896 ("admin_level", PropValue::Str("2".into())),
897 ("disputed", PropValue::Str("yes".into())),
898 ],
899 vec![],
900 );
901 let result = process(&feat).unwrap();
902 assert_eq!(result.sort_rank, 288);
903 }
904
905 #[test]
906 fn osm_no_relations_boundary_claim() {
907 let feat = make_osm_way(
908 &[
909 ("boundary", PropValue::Str("claim".into())),
910 ("admin_level", PropValue::Str("2".into())),
911 ],
912 vec![],
913 );
914 assert!(process(&feat).is_none());
917 }
918
919 #[test]
920 fn osm_no_relations_india_level_2_suppressed() {
921 let mut feat = make_osm_way(
922 &[
923 ("boundary", PropValue::Str("administrative".into())),
924 ("admin_level", PropValue::Str("2".into())),
925 ],
926 vec![],
927 );
928 feat.bbox = Some([78.0, 20.0, 80.0, 22.0]); assert!(process(&feat).is_none());
930 }
931
932 #[test]
933 fn osm_no_relations_india_level_2_disputed_kept() {
934 let mut feat = make_osm_way(
935 &[
936 ("boundary", PropValue::Str("disputed".into())),
937 ("admin_level", PropValue::Str("2".into())),
938 ],
939 vec![],
940 );
941 feat.bbox = Some([78.0, 20.0, 80.0, 22.0]);
942 let result = process(&feat).unwrap();
943 assert_eq!(result.sort_rank, 288);
944 }
945
946 #[test]
947 fn osm_no_relations_india_level_4_kept() {
948 let mut feat = make_osm_way(
949 &[
950 ("boundary", PropValue::Str("administrative".into())),
951 ("admin_level", PropValue::Str("4".into())),
952 ],
953 vec![],
954 );
955 feat.bbox = Some([78.0, 20.0, 80.0, 22.0]);
956 assert!(process(&feat).is_some());
957 }
958
959 #[test]
960 fn osm_relations_picks_lowest_admin_level() {
961 let feat = make_osm_way(
962 &[],
963 vec![
964 rel_with(Some(6), false, &[("type", "boundary")]),
965 rel_with(Some(2), false, &[("type", "boundary")]),
966 rel_with(Some(4), false, &[("type", "boundary")]),
967 ],
968 );
969 let result = process(&feat).unwrap();
970 assert!(
971 result
972 .properties
973 .iter()
974 .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
975 );
976 }
977
978 #[test]
979 fn osm_relations_filter_boundary_administrative() {
980 let feat = make_osm_way(
981 &[],
982 vec![rel_with(Some(4), false, &[("boundary", "administrative")])],
983 );
984 let result = process(&feat).unwrap();
985 assert!(
986 result
987 .properties
988 .iter()
989 .any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
990 );
991 }
992
993 #[test]
994 fn osm_relations_filter_boundary_disputed() {
995 let feat = make_osm_way(
996 &[],
997 vec![rel_with(Some(2), false, &[("boundary", "disputed")])],
998 );
999 let result = process(&feat).unwrap();
1000 assert_eq!(result.sort_rank, 288);
1001 }
1002
1003 #[test]
1004 fn osm_relations_no_match_returns_none() {
1005 let feat = make_osm_way(
1006 &[],
1007 vec![rel_with(Some(2), false, &[("type", "multipolygon")])],
1008 );
1009 assert!(process(&feat).is_none());
1010 }
1011
1012 #[test]
1013 fn osm_relations_admin_level_default_when_missing() {
1014 let feat = make_osm_way(&[], vec![rel_with(None, false, &[("type", "boundary")])]);
1015 let result = process(&feat).unwrap();
1016 assert!(
1017 result
1018 .properties
1019 .iter()
1020 .any(|(k, v)| k == "kind_detail" && *v == PropValue::I64(2))
1021 );
1022 }
1023
1024 #[test]
1025 fn osm_relations_dropped_admin_level_returns_none() {
1026 let feat = make_osm_way(&[], vec![rel_with(Some(9), false, &[("type", "boundary")])]);
1027 assert!(process(&feat).is_none());
1028 }
1029
1030 #[test]
1033 fn osm_relations_disputed_by_flag_claim_or_disputed_tag() {
1034 let relations = [
1035 rel_with(Some(2), true, &[("type", "boundary")]),
1036 rel_with(
1037 Some(2),
1038 false,
1039 &[("type", "boundary"), ("boundary", "claim")],
1040 ),
1041 rel_with(Some(2), false, &[("type", "boundary"), ("disputed", "yes")]),
1042 ];
1043 for rel in relations {
1044 let tags = format!("{:?}", rel.tags);
1045 let result = process(&make_osm_way(&[], vec![rel])).expect("a boundary");
1046 assert_eq!(result.sort_rank, 288, "{tags}");
1047 }
1048 }
1049
1050 #[test]
1051 fn osm_relations_india_level_2_suppressed() {
1052 let mut feat = make_osm_way(&[], vec![rel_with(Some(2), false, &[("type", "boundary")])]);
1053 feat.bbox = Some([78.0, 20.0, 80.0, 22.0]);
1054 assert!(process(&feat).is_none());
1055 }
1056
1057 #[test]
1058 fn osm_relations_india_level_2_disputed_kept() {
1059 let mut feat = make_osm_way(&[], vec![rel_with(Some(2), true, &[("type", "boundary")])]);
1060 feat.bbox = Some([78.0, 20.0, 80.0, 22.0]);
1061 let result = process(&feat).unwrap();
1062 assert_eq!(result.sort_rank, 288);
1063 }
1064
1065 #[test]
1066 fn osm_relations_disputed_by_property_added() {
1067 let feat = make_osm_way(
1068 &[("disputed_by", PropValue::Str("CountryX".into()))],
1069 vec![rel_with(Some(2), true, &[("type", "boundary")])],
1070 );
1071 let result = process(&feat).unwrap();
1072 assert!(
1073 result
1074 .properties
1075 .iter()
1076 .any(|(k, v)| k == "disputed_by" && *v == PropValue::Str("CountryX".into()))
1077 );
1078 }
1079
1080 #[test]
1081 fn osm_relations_claimed_by_property_added() {
1082 let feat = make_osm_way(
1083 &[("claimed_by", PropValue::Str("CountryY".into()))],
1084 vec![rel_with(Some(2), true, &[("type", "boundary")])],
1085 );
1086 let result = process(&feat).unwrap();
1087 assert!(
1088 result
1089 .properties
1090 .iter()
1091 .any(|(k, v)| k == "claimed_by" && *v == PropValue::Str("CountryY".into()))
1092 );
1093 }
1094
1095 fn square_mask() -> IndiaMask {
1100 let ring = geo::LineString::from(vec![
1101 (0.0, 0.0),
1102 (10.0, 0.0),
1103 (10.0, 10.0),
1104 (0.0, 10.0),
1105 (0.0, 0.0),
1106 ]);
1107 let feat = InputFeature {
1108 geometry: Arc::new(geo::Geometry::MultiLineString(geo::MultiLineString::new(
1109 vec![ring],
1110 ))),
1111 ..make_india_feature(&[])
1112 };
1113 IndiaMask::from_features(&[feat]).unwrap()
1114 }
1115
1116 fn country_line(coords: Vec<(f64, f64)>, disputed: bool) -> ProcessedFeature {
1117 let mut props = vec![("subtype", PropValue::Str("country".into()))];
1118 if disputed {
1119 props.push(("is_disputed", PropValue::Bool(true)));
1120 }
1121 let mut feat = make_feature(&props);
1122 feat.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(coords)));
1123 process(&feat).unwrap()
1124 }
1125
1126 fn total_length(feature: &ProcessedFeature) -> f64 {
1127 use geo::{Euclidean, Length};
1128 match feature.geometry.as_ref() {
1129 geo::Geometry::MultiLineString(m) => Euclidean.length(m),
1130 geo::Geometry::LineString(l) => Euclidean.length(l),
1131 other => panic!("unexpected geometry {other:?}"),
1132 }
1133 }
1134
1135 #[test]
1138 fn india_mask_keeps_only_the_country_line_outside_india() {
1139 let line = country_line(vec![(-5.0, 5.0), (15.0, 5.0)], false);
1140 let clipped = square_mask().clip(line).unwrap();
1141 let expected = 2.0 * (5.0 - MASK_MARGIN_DEG);
1142 assert!((total_length(&clipped) - expected).abs() < 1e-6);
1143 }
1144
1145 #[test]
1148 fn india_mask_drops_country_lines_inside_india() {
1149 let mask = square_mask();
1150 for disputed in [false, true] {
1151 let line = country_line(vec![(2.0, 2.0), (8.0, 8.0)], disputed);
1152 assert!(mask.clip(line).is_none(), "disputed={disputed}");
1153 }
1154 }
1155
1156 #[test]
1159 fn india_mask_drops_a_copy_of_the_border_inside_the_margin() {
1160 let line = country_line(vec![(-0.001, 2.0), (-0.001, 8.0)], false);
1161 assert!(square_mask().clip(line).is_none());
1162 }
1163
1164 #[test]
1165 fn india_mask_leaves_regions_and_far_lines_alone() {
1166 let mask = square_mask();
1167 let mut region = make_feature(&[("subtype", PropValue::Str("region".into()))]);
1168 region.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
1169 (2.0, 2.0),
1170 (8.0, 8.0),
1171 ])));
1172 let region = process(®ion).unwrap();
1173 let kept = mask.clip(region.clone()).unwrap();
1174 assert!(Arc::ptr_eq(&kept.geometry, ®ion.geometry));
1175
1176 let far = country_line(vec![(40.0, 40.0), (50.0, 50.0)], false);
1177 let kept = mask.clip(far.clone()).unwrap();
1178 assert!(Arc::ptr_eq(&kept.geometry, &far.geometry));
1179 }
1180
1181 #[test]
1182 fn india_mask_needs_a_closed_ring() {
1183 assert!(IndiaMask::from_features(&[make_india_feature(&[])]).is_none());
1184 }
1185
1186 #[test]
1187 fn india_default_kind_and_detail() {
1188 let feat = make_india_feature(&[]);
1189 let result = process(&feat).unwrap();
1190 assert_eq!(result.layer, Layer::Boundaries);
1191 assert_eq!(result.min_zoom, 0);
1193 assert_eq!(result.max_zoom, 15);
1194 assert_eq!(result.sort_rank, 289);
1195 assert!(
1196 result
1197 .properties
1198 .iter()
1199 .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
1200 );
1201 assert!(
1202 result
1203 .properties
1204 .iter()
1205 .any(|(k, v)| k == "kind_detail" && *v == PropValue::I64(2))
1206 );
1207 }
1208
1209 #[test]
1210 fn india_custom_kind_and_detail() {
1211 let feat = make_india_feature(&[
1212 ("kind", PropValue::Str("region".into())),
1213 ("kind_detail", PropValue::I64(4)),
1214 ]);
1215 let result = process(&feat).unwrap();
1216 assert!(
1217 result
1218 .properties
1219 .iter()
1220 .any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
1221 );
1222 assert!(
1223 result
1224 .properties
1225 .iter()
1226 .any(|(k, v)| k == "kind_detail" && *v == PropValue::I64(4))
1227 );
1228 }
1229
1230 #[test]
1231 fn india_with_name_property() {
1232 let feat = make_india_feature(&[("name", PropValue::Str("India".into()))]);
1233 let result = process(&feat).unwrap();
1234 assert!(
1235 result
1236 .properties
1237 .iter()
1238 .any(|(k, v)| k == "name" && *v == PropValue::Str("India".into()))
1239 );
1240 }
1241
1242 #[test]
1245 fn admin_level_to_kind_all_branches() {
1246 assert_eq!(admin_level_to_kind(2), Some(("country", 6)));
1247 assert_eq!(admin_level_to_kind(3), Some(("region", 6)));
1248 assert_eq!(admin_level_to_kind(4), Some(("region", 6)));
1249 assert_eq!(admin_level_to_kind(5), Some(("county", 8)));
1250 assert_eq!(admin_level_to_kind(6), Some(("county", 8)));
1251 assert_eq!(admin_level_to_kind(7), Some(("locality", 10)));
1252 assert_eq!(admin_level_to_kind(8), Some(("locality", 10)));
1253 assert_eq!(admin_level_to_kind(0), None);
1254 assert_eq!(admin_level_to_kind(1), None);
1255 assert_eq!(admin_level_to_kind(9), None);
1256 assert_eq!(admin_level_to_kind(100), None);
1257 assert_eq!(admin_level_to_kind(-1), None);
1258 }
1259
1260 #[test]
1263 fn india_bbox_centroid_inside() {
1264 let feat = InputFeature {
1265 id: 1,
1266 geometry: line_geom(),
1267 properties: HashMap::new(),
1268 bbox: Some([77.0, 20.0, 79.0, 22.0]),
1269 source: DataSource::IndiaBoundary,
1270 };
1271 assert!(is_within_india_bbox(&feat));
1272 }
1273
1274 #[test]
1275 fn india_bbox_centroid_outside() {
1276 let feat = InputFeature {
1277 id: 1,
1278 geometry: line_geom(),
1279 properties: HashMap::new(),
1280 bbox: Some([0.0, 0.0, 1.0, 1.0]),
1281 source: DataSource::IndiaBoundary,
1282 };
1283 assert!(!is_within_india_bbox(&feat));
1284 }
1285
1286 #[test]
1287 fn india_bbox_fallback_linestring_inside() {
1288 let feat = InputFeature {
1289 id: 1,
1290 geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
1291 (78.0, 20.0),
1292 (79.0, 22.0),
1293 ]))),
1294 properties: HashMap::new(),
1295 bbox: None,
1296 source: DataSource::IndiaBoundary,
1297 };
1298 assert!(is_within_india_bbox(&feat));
1299 }
1300
1301 #[test]
1302 fn india_bbox_fallback_linestring_outside() {
1303 let feat = InputFeature {
1304 id: 1,
1305 geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
1306 (0.0, 0.0),
1307 (1.0, 1.0),
1308 ]))),
1309 properties: HashMap::new(),
1310 bbox: None,
1311 source: DataSource::IndiaBoundary,
1312 };
1313 assert!(!is_within_india_bbox(&feat));
1314 }
1315
1316 #[test]
1317 fn india_bbox_fallback_empty_linestring() {
1318 let feat = InputFeature {
1319 id: 1,
1320 geometry: Arc::new(geo::Geometry::LineString(geo::LineString::from(Vec::<(
1321 f64,
1322 f64,
1323 )>::new(
1324 )))),
1325 properties: HashMap::new(),
1326 bbox: None,
1327 source: DataSource::IndiaBoundary,
1328 };
1329 assert!(!is_within_india_bbox(&feat));
1330 }
1331
1332 #[test]
1333 fn india_bbox_fallback_point_inside() {
1334 let feat = InputFeature {
1335 id: 1,
1336 geometry: Arc::new(geo::Geometry::Point(geo::Point::new(78.0, 20.0))),
1337 properties: HashMap::new(),
1338 bbox: None,
1339 source: DataSource::IndiaBoundary,
1340 };
1341 assert!(is_within_india_bbox(&feat));
1342 }
1343
1344 #[test]
1345 fn india_bbox_fallback_point_outside() {
1346 let feat = InputFeature {
1347 id: 1,
1348 geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
1349 properties: HashMap::new(),
1350 bbox: None,
1351 source: DataSource::IndiaBoundary,
1352 };
1353 assert!(!is_within_india_bbox(&feat));
1354 }
1355
1356 #[test]
1357 fn india_bbox_fallback_other_geom() {
1358 let feat = InputFeature {
1359 id: 1,
1360 geometry: Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
1361 geo::LineString::from(vec![(78.0, 20.0), (79.0, 20.0), (79.0, 21.0), (78.0, 20.0)]),
1362 vec![],
1363 ))),
1364 properties: HashMap::new(),
1365 bbox: None,
1366 source: DataSource::IndiaBoundary,
1367 };
1368 assert!(!is_within_india_bbox(&feat));
1370 }
1371}