1use std::f64::consts::PI;
7
8use feature::Value as MbglValue;
9use geo_types::{Coord, Geometry, Polygon};
10use geojson::GeoJson;
11use geometry::Point;
12use mln_conversion::{Convertible, Error};
13use mln_tile_id::CanonicalTileID;
14use mln_tile_id::geometry_tile_data::{GeometryCoordinates, GeometryTileFeature};
15use mln_util::constants::{DEGREES_MAX, EXTENT, LONGITUDE_MAX};
16use mln_util::geometry::{FeatureType, to_feature_type};
17use mln_util::logging::{Event, Log};
18
19use crate::expression::{EvaluationContext, Expr, Node};
20use crate::parsing_context::{ParseResult, ParsingContext};
21
22type WithinBBox = [i64; 4];
26const DEFAULT_WITHIN_BBOX: WithinBBox = [i64::MAX, i64::MAX, i64::MIN, i64::MIN];
27
28type TilePolygon = Vec<Vec<Point<i64>>>;
29
30fn update_bbox(bbox: &mut WithinBBox, p: &Point<i64>) {
31 bbox[0] = bbox[0].min(p.x);
32 bbox[1] = bbox[1].min(p.y);
33 bbox[2] = bbox[2].max(p.x);
34 bbox[3] = bbox[3].max(p.y);
35}
36
37fn box_within_box(bbox1: &WithinBBox, bbox2: &WithinBBox) -> bool {
39 if bbox1[0] <= bbox2[0] {
40 return false;
41 }
42 if bbox1[2] >= bbox2[2] {
43 return false;
44 }
45 if bbox1[1] <= bbox2[1] {
46 return false;
47 }
48 if bbox1[3] >= bbox2[3] {
49 return false;
50 }
51 true
52}
53
54fn ray_intersect(p: &Point<i64>, p1: &Point<i64>, p2: &Point<i64>) -> bool {
55 ((p1.y > p.y) != (p2.y > p.y))
56 && (p.x
57 < (p2.x.wrapping_sub(p1.x))
58 .wrapping_mul(p.y.wrapping_sub(p1.y))
59 .wrapping_div(p2.y.wrapping_sub(p1.y))
60 .wrapping_add(p1.x))
61}
62
63fn point_on_boundary(p: &Point<i64>, p1: &Point<i64>, p2: &Point<i64>) -> bool {
65 let x1 = p.x.wrapping_sub(p1.x);
70 let y1 = p.y.wrapping_sub(p1.y);
71 let x2 = p.x.wrapping_sub(p2.x);
72 let y2 = p.y.wrapping_sub(p2.y);
73 (x1.wrapping_mul(y2).wrapping_sub(x2.wrapping_mul(y1)) == 0)
74 && (x1.wrapping_mul(x2) <= 0)
75 && (y1.wrapping_mul(y2) <= 0)
76}
77
78fn segment_intersect_segment(a: &Point<i64>, b: &Point<i64>, c: &Point<i64>, d: &Point<i64>) -> bool {
79 let perp = |v1: &Point<i64>, v2: &Point<i64>| v1.x.wrapping_mul(v2.y).wrapping_sub(v1.y.wrapping_mul(v2.x));
82
83 let vector_p = Point::new(b.x.wrapping_sub(a.x), b.y.wrapping_sub(a.y));
87 let vector_q = Point::new(d.x.wrapping_sub(c.x), d.y.wrapping_sub(c.y));
88 if perp(&vector_q, &vector_p) == 0 {
89 return false;
90 }
91
92 let two_sided = |p1: &Point<i64>, p2: &Point<i64>, q1: &Point<i64>, q2: &Point<i64>| {
94 let x1 = p1.x.wrapping_sub(q1.x);
96 let y1 = p1.y.wrapping_sub(q1.y);
97 let x2 = p2.x.wrapping_sub(q1.x);
98 let y2 = p2.y.wrapping_sub(q1.y);
99 let x3 = q2.x.wrapping_sub(q1.x);
100 let y3 = q2.y.wrapping_sub(q1.y);
101 let ret1 = x1.wrapping_mul(y3).wrapping_sub(x3.wrapping_mul(y1));
102 let ret2 = x2.wrapping_mul(y3).wrapping_sub(x3.wrapping_mul(y2));
103 (ret1 > 0 && ret2 < 0) || (ret1 < 0 && ret2 > 0)
104 };
105
106 two_sided(a, b, c, d) && two_sided(c, d, a, b)
110}
111
112fn line_intersect_polygon(p1: &Point<i64>, p2: &Point<i64>, polygon: &TilePolygon) -> bool {
113 polygon.iter().any(|ring| ring.windows(2).any(|edge| segment_intersect_segment(p1, p2, &edge[0], &edge[1])))
115}
116
117fn point_within_polygon(point: &Point<i64>, polygon: &TilePolygon, true_on_boundary: bool) -> bool {
119 let mut within = false;
120 for ring in polygon {
121 for edge in ring.windows(2) {
123 if point_on_boundary(point, &edge[0], &edge[1]) {
124 return true_on_boundary;
125 }
126 if ray_intersect(point, &edge[0], &edge[1]) {
127 within = !within;
128 }
129 }
130 }
131 within
132}
133
134fn point_within_polygons(point: &Point<i64>, polygons: &[TilePolygon], true_on_boundary: bool) -> bool {
135 polygons.iter().any(|polygon| point_within_polygon(point, polygon, true_on_boundary))
136}
137
138fn line_string_within_polygon(line: &[Point<i64>], polygon: &TilePolygon) -> bool {
139 if !line.iter().all(|point| point_within_polygon(point, polygon, false)) {
141 return false;
142 }
143
144 !line.windows(2).any(|segment| line_intersect_polygon(&segment[0], &segment[1], polygon))
146}
147
148fn line_string_within_polygons(line: &[Point<i64>], polygons: &[TilePolygon]) -> bool {
149 polygons.iter().any(|polygon| line_string_within_polygon(line, polygon))
150}
151
152fn lat_lon_to_tile_coordinates(point: &Coord<f64>, canonical: &CanonicalTileID) -> Point<i64> {
153 let size = f64::from(EXTENT) * 2f64.powi(i32::from(canonical.z));
154
155 let x = (point.x + LONGITUDE_MAX) * size / DEGREES_MAX;
156 let y =
157 (LONGITUDE_MAX - mln_math::rad2deg((point.y * PI / DEGREES_MAX + PI / 4.0).tan().ln())) * size / DEGREES_MAX;
158
159 Point::new(x as i64, y as i64)
162}
163
164fn get_tile_polygon(polygon: &Polygon<f64>, canonical: &CanonicalTileID, bbox: &mut WithinBBox) -> TilePolygon {
165 let mut result = Vec::with_capacity(1 + polygon.interiors().len());
166 for ring in std::iter::once(polygon.exterior()).chain(polygon.interiors()) {
167 let mut temp = Vec::with_capacity(ring.0.len());
168 for p in &ring.0 {
169 let coord = lat_lon_to_tile_coordinates(p, canonical);
170 temp.push(coord);
171 update_bbox(bbox, &coord);
172 }
173 result.push(temp);
174 }
175 result
176}
177
178fn get_tile_polygons(
179 polygon_geo_set: &Geometry<f64>,
180 canonical: &CanonicalTileID,
181 bbox: &mut WithinBBox,
182) -> Vec<TilePolygon> {
183 match polygon_geo_set {
184 Geometry::MultiPolygon(polygons) => polygons.iter().map(|pg| get_tile_polygon(pg, canonical, bbox)).collect(),
185 Geometry::Polygon(polygon) => vec![get_tile_polygon(polygon, canonical, bbox)],
186 Geometry::Rect(rect) => vec![get_tile_polygon(&rect.to_polygon(), canonical, bbox)],
187 Geometry::Triangle(triangle) => vec![get_tile_polygon(&triangle.to_polygon(), canonical, bbox)],
188 _ => Vec::new(),
189 }
190}
191
192fn update_point(p: &mut Point<i64>, bbox: &mut WithinBBox, poly_bbox: &WithinBBox, world_size: i64) {
193 if p.x < poly_bbox[0] || p.x > poly_bbox[2] {
194 let get_shift = |point: &Point<i64>, polygon_side: i64, size: i64| -> i64 {
195 if point.x.wrapping_sub(polygon_side) > size / 2 {
196 return -size;
197 }
198 if polygon_side.wrapping_sub(point.x) > size / 2 {
199 return size;
200 }
201 0
202 };
203
204 let mut shift = get_shift(p, poly_bbox[0], world_size);
205 if shift == 0 {
206 shift = get_shift(p, poly_bbox[2], world_size);
207 }
208 p.x = p.x.wrapping_add(shift);
209 }
210 update_bbox(bbox, p);
211}
212
213fn tile_shift(coordinate: u32) -> i64 {
216 i64::from((EXTENT as u32).wrapping_mul(coordinate))
217}
218
219fn world_size(canonical: &CanonicalTileID) -> i64 {
220 (f64::from(EXTENT) * 2f64.powi(i32::from(canonical.z))) as i64
221}
222
223fn get_tile_points(
224 points: &GeometryCoordinates,
225 canonical: &CanonicalTileID,
226 bbox: &mut WithinBBox,
227 poly_bbox: &WithinBBox,
228) -> Vec<Point<i64>> {
229 let x_shift = tile_shift(canonical.x);
230 let y_shift = tile_shift(canonical.y);
231 let world_size = world_size(canonical);
232 let mut results = Vec::with_capacity(points.len());
233 for p in points {
234 let mut point = Point::new(i64::from(p.x) + x_shift, i64::from(p.y) + y_shift);
235 update_point(&mut point, bbox, poly_bbox, world_size);
236 results.push(point);
237 }
238 results
239}
240
241fn get_tile_lines(
242 lines: &[GeometryCoordinates],
243 canonical: &CanonicalTileID,
244 bbox: &mut WithinBBox,
245 poly_bbox: &WithinBBox,
246) -> Vec<Vec<Point<i64>>> {
247 let x_shift = tile_shift(canonical.x);
248 let y_shift = tile_shift(canonical.y);
249 let mut results = Vec::with_capacity(lines.len());
250 for line in lines {
251 let mut line_string = Vec::with_capacity(line.len());
252 for p in line {
253 let point = Point::new(i64::from(p.x) + x_shift, i64::from(p.y) + y_shift);
254 update_bbox(bbox, &point);
255 line_string.push(point);
256 }
257 results.push(line_string);
258 }
259
260 let world_size = world_size(canonical);
261 if bbox[2].wrapping_sub(bbox[0]) <= world_size / 2 {
262 *bbox = DEFAULT_WITHIN_BBOX;
263 for line in &mut results {
264 for p in line.iter_mut() {
265 update_point(p, bbox, poly_bbox, world_size);
266 }
267 }
268 }
269 results
270}
271
272fn feature_within_polygons(
273 feature: &dyn GeometryTileFeature,
274 canonical: &CanonicalTileID,
275 polygon_geo_set: &Geometry<f64>,
276) -> bool {
277 let mut poly_bbox = DEFAULT_WITHIN_BBOX;
278 let polygons = get_tile_polygons(polygon_geo_set, canonical, &mut poly_bbox);
279 if polygons.is_empty() {
281 return false;
282 }
283 let Ok(geometries) = feature.get_geometries() else {
285 return false;
286 };
287 match feature.get_type() {
288 FeatureType::Point => {
289 let Some(first) = geometries.first() else {
292 return false;
293 };
294 let mut point_bbox = DEFAULT_WITHIN_BBOX;
295 let points = get_tile_points(first, canonical, &mut point_bbox, &poly_bbox);
296 if !box_within_box(&point_bbox, &poly_bbox) {
297 return false;
298 }
299
300 points.iter().all(|p| point_within_polygons(p, &polygons, false))
301 }
302 FeatureType::LineString => {
303 let mut line_bbox = DEFAULT_WITHIN_BBOX;
304 let multi_line_string = get_tile_lines(&geometries, canonical, &mut line_bbox, &poly_bbox);
305 if !box_within_box(&line_bbox, &poly_bbox) {
306 return false;
307 }
308
309 multi_line_string.iter().all(|line| line_string_within_polygons(line, &polygons))
310 }
311 _ => false,
312 }
313}
314
315const POLYGON_REQUIRED: &str = "'within' expression requires valid geojson source that contains polygon geometry type.";
316
317fn parse_value(value: &Convertible<'_>, ctx: &mut ParsingContext) -> Option<GeoJson> {
318 if value.is_object() {
319 let mut error = Error::default();
320 let geojson = value.to_geojson(&mut error);
321 if let Some(geojson) = geojson
322 && error.message.is_empty()
323 {
324 return Some(geojson);
325 }
326 ctx.error(error.message);
327 }
328
329 ctx.error(POLYGON_REQUIRED.to_owned());
330 None
331}
332
333fn get_polygon_info(geometry: Option<&geojson::Geometry>, ctx: &mut ParsingContext) -> Option<Geometry<f64>> {
334 match geometry.map(|g| feature::geojson::geometry(g.clone())) {
335 Some(Ok(geometry)) if to_feature_type(Some(&geometry)) == FeatureType::Polygon => return Some(geometry),
336 Some(Err(e)) => {
337 ctx.error(e.to_string());
338 return None;
339 }
340 _ => {}
341 }
342 ctx.error(POLYGON_REQUIRED.to_owned());
343 None
344}
345
346pub(crate) fn geojson_geometries(geojson: &GeoJson) -> Vec<Option<&geojson::Geometry>> {
348 match geojson {
349 GeoJson::Geometry(geometry) => vec![Some(geometry)],
350 GeoJson::Feature(feature) => vec![feature.geometry.as_ref()],
351 GeoJson::FeatureCollection(collection) => collection.features.iter().map(|f| f.geometry.as_ref()).collect(),
352 }
353}
354
355#[derive(Clone, PartialEq)]
357pub(crate) struct Within {
358 geojson_source: GeoJson,
359 geometries: Geometry<f64>,
360}
361
362impl mln_wire::Wire for Within {
365 fn write(&self, w: &mut mln_wire::Writer) {
366 self.source_value().write(w);
367 }
368
369 fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
370 Within::try_from(MbglValue::read(r)?).ok().or_else(|| r.fail("invalid within GeoJSON"))
371 }
372}
373
374impl TryFrom<MbglValue> for Within {
375 type Error = String;
376
377 fn try_from(value: MbglValue) -> Result<Self, String> {
378 let mut ctx = ParsingContext::without_functions();
379 parse_value(&Convertible::from(&value), &mut ctx)
380 .and_then(|geojson_source| Within::from_source(geojson_source, &mut ctx))
381 .ok_or_else(|| ctx.get_combined_errors())
382 }
383}
384
385impl From<Within> for MbglValue {
386 fn from(within: Within) -> Self {
387 within.source_value()
388 }
389}
390
391impl Within {
392 pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
393 if value.array_length() != 2 {
395 ctx.error(format!(
396 "'within' expression requires exactly one argument, but found {} instead.",
397 value.array_length() - 1
398 ));
399 return None;
400 }
401
402 let parsed_value = parse_value(&value.array_member(1), ctx)?;
403 Within::from_source(parsed_value, ctx).map(|within| Expr::new(Node::Within(Box::new(within))))
404 }
405
406 fn from_source(geojson_source: GeoJson, ctx: &mut ParsingContext) -> Option<Within> {
409 let candidates = geojson_geometries(&geojson_source);
410 let found = candidates.iter().find_map(|geometry| get_polygon_info(*geometry, ctx));
411 if candidates.is_empty() {
413 ctx.error(POLYGON_REQUIRED.to_owned());
414 }
415 Some(Within { geometries: found?, geojson_source })
416 }
417}
418
419impl Within {
420 pub(crate) fn eval_bool(&self, params: &EvaluationContext<'_>) -> bool {
421 let (Some(feature), Some(canonical)) = (params.feature, params.canonical) else {
422 return false;
423 };
424 let geometry_type = feature.get_type();
425 if geometry_type == FeatureType::Point || geometry_type == FeatureType::LineString {
427 return feature_within_polygons(feature, canonical, &self.geometries);
428 }
429 Log::warning(Event::General, "within expression currently only support Point/LineString geometry type.");
430
431 false
432 }
433
434 pub(crate) fn serialize(&self) -> MbglValue {
435 MbglValue::Array(vec![MbglValue::String("within".to_owned()), self.source_value()])
436 }
437
438 fn source_value(&self) -> MbglValue {
440 mln_conversion::json_to_value(&serde_json::to_value(&self.geojson_source).unwrap_or_default())
441 }
442}
443
444#[cfg(test)]
445mod tests {
446 use std::borrow::Cow;
447
448 use super::*;
449 use crate::Functions;
450 use crate::value::Value;
451
452 #[test]
453 fn empty_feature_collection_is_a_parse_error() {
454 let document = serde_json::json!(["within", {"type": "FeatureCollection", "features": []}]);
455 let mut ctx = ParsingContext::new(&Functions::with_builtins());
456 assert!(ctx.parse_expression(&Convertible::from(&document), None).is_none());
457 assert_eq!(ctx.get_errors().len(), 1);
458 assert_eq!(ctx.get_errors()[0].message, POLYGON_REQUIRED);
459 }
460
461 struct PointFeature(mln_tile_id::geometry_tile_data::GeometryCollection);
462
463 impl GeometryTileFeature for PointFeature {
464 fn get_type(&self) -> FeatureType {
465 FeatureType::Point
466 }
467
468 fn get_value(&self, _key: &str) -> Option<MbglValue> {
469 None
470 }
471
472 fn get_geometries(
473 &self,
474 ) -> Result<Cow<'_, mln_tile_id::geometry_tile_data::GeometryCollection>, mln_util::error::Error> {
475 Ok(Cow::Borrowed(&self.0))
476 }
477 }
478
479 #[test]
481 fn nothing_is_within_an_empty_multi_polygon() {
482 let document = serde_json::json!(["within", {"type": "MultiPolygon", "coordinates": []}]);
483 let mut ctx = ParsingContext::new(&Functions::with_builtins());
484 let within = ctx.parse_expression(&Convertible::from(&document), None).expect("parses");
485 let feature = PointFeature(vec![vec![Point::new(10, 10)]].into());
486 let canonical = CanonicalTileID::new(3, 3, 3);
487 let params = EvaluationContext::from_feature(Some(&feature)).with_canonical_tile_id(Some(&canonical));
488 assert_eq!(within.evaluate(¶ms), Ok(Value::Bool(false)));
489 }
490}