Skip to main content

jagua_rs/geometry/
shape_modification.rs

1use geo::Buffer;
2use geo::algorithm::Area;
3use geo::algorithm::buffer::{BufferStyle, LineJoin};
4use itertools::Itertools;
5use log::{debug, error, info, warn};
6use ordered_float::OrderedFloat;
7use serde::{Deserialize, Serialize};
8use std::cmp::Ordering;
9
10use crate::geometry::geo_traits::{CollidesWith, DistanceTo};
11use crate::geometry::primitives::Edge;
12use crate::geometry::primitives::Point;
13use crate::geometry::primitives::Rect;
14use crate::geometry::primitives::SPolygon;
15use crate::geometry::short_edges::has_short_edges;
16
17use anyhow::{Result, bail};
18
19/// Whether to strictly inflate or deflate when making any modifications to shape.
20/// Depends on the [`scope`](crate::collision_detection::hazards::HazardEntity::scope) of the [`HazardEntity`](crate::collision_detection::hazards::HazardEntity) that the shape represents.
21#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]
22pub enum ShapeModifyMode {
23    /// Modify the shape to be strictly larger than the original (superset).
24    Inflate,
25    /// Modify the shape to be strictly smaller than the original (subset).
26    Deflate,
27}
28
29#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq)]
30/// Shape modification settings. Supplied distances and ratios must be finite and nonnegative.
31pub struct ShapeModifyConfig {
32    /// Maximum deviation of the simplified polygon with respect to the original polygon area as a ratio.
33    /// If undefined, no simplification is performed.
34    /// See [`simplify_shape`]
35    pub simplify_tolerance: Option<f32>,
36    /// Offset by which to inflate or deflate the polygon.
37    /// If undefined, no offset is applied.
38    /// See [`offset_shape`]
39    pub offset: Option<f32>,
40    /// Definition for narrow concavities that can be closed by a straight edge.
41    /// Defined as a tuple of (`max_distance_ratio`, `max_area_ratio`) where:
42    /// - `max_distance_ratio`: maximum distance between two vertices of a polygon to consider it a narrow concavity, defined as a fraction of the item's diameter.
43    /// - `max_area_ratio`: maximum area of the sub-shape formed by the vertices between the two vertices, defined as a fraction of the item's area.
44    ///
45    /// If undefined, no narrow concavities will be closed.
46    /// See [`close_narrow_concavities`]
47    pub narrow_concavity_cutoff: Option<(f32, f32)>,
48}
49
50/// Simplifies a [`SPolygon`] by reducing the number of edges.
51///
52/// The simplified shape will either be a subset or a superset of the original shape, depending on the [`ShapeModifyMode`].
53/// Its bounding box never exceeds that of the original shape.
54/// The procedure sequentially eliminates edges until either the change in area (ratio)
55/// exceeds `max_area_delta` or the number of edges < 4.
56pub fn simplify_shape(
57    shape: &SPolygon,
58    mode: ShapeModifyMode,
59    max_area_change_ratio: f32,
60) -> SPolygon {
61    let original_area = shape.area;
62
63    let mut ref_points = shape.vertices.clone();
64
65    for _ in 0..shape.n_vertices() {
66        let n_points = ref_points.len().cast_signed();
67        if n_points < 4 {
68            //can't simplify further
69            break;
70        }
71
72        let mut corners = (0..n_points)
73            .map(|i| {
74                let i_prev = (i - 1).rem_euclid(n_points);
75                let i_next = (i + 1).rem_euclid(n_points);
76                Corner(
77                    i_prev.cast_unsigned(),
78                    i.cast_unsigned(),
79                    i_next.cast_unsigned(),
80                )
81            })
82            .collect_vec();
83
84        if mode == ShapeModifyMode::Deflate {
85            //default mode is to inflate, so we need to reverse the order of the corners and flip the corners for deflate mode
86            //reverse the order of the corners
87            corners.reverse();
88            //reverse each corner
89            corners.iter_mut().for_each(Corner::flip);
90        }
91
92        let mut candidates = vec![];
93
94        let mut prev_corner = corners.last().expect("corners is empty");
95        let mut prev_corner_type = CornerType::from(prev_corner.to_points(&ref_points));
96
97        //Go over all corners and generate candidates
98        for corner in &corners {
99            let corner_type = CornerType::from(corner.to_points(&ref_points));
100
101            //Generate a removal candidate (or not)
102            match (&corner_type, &prev_corner_type) {
103                (CornerType::Concave, _) => candidates.push(Candidate::Concave(*corner)),
104                (CornerType::Collinear, _) => candidates.push(Candidate::Collinear(*corner)),
105                (CornerType::Convex, CornerType::Convex) => {
106                    candidates.push(Candidate::ConvexConvex(*prev_corner, *corner));
107                }
108                (_, _) => {}
109            }
110            (prev_corner, prev_corner_type) = (corner, corner_type);
111        }
112
113        //search the candidate with the smallest change in area that is valid
114        //and does not leave edges that SPolygon::new would remove.
115        //The minimum edge length depends on the diameter of the result, which a replacing vertex can grow.
116        let best_candidate = candidates
117            .iter()
118            .sorted_by_cached_key(|c| {
119                OrderedFloat(calculate_area_delta(&ref_points, c).unwrap_or(f32::INFINITY))
120            })
121            .filter(|c| candidate_is_valid(&ref_points, c, &shape.bbox))
122            .map(|c| (c, execute_candidate(&ref_points, c)))
123            .find(|(_, new_shape)| !has_short_edges(new_shape));
124
125        //if it is within the area change constraints, execute the candidate
126        if let Some((best_candidate, new_shape)) = best_candidate {
127            let new_shape_area = SPolygon::calculate_area(&new_shape);
128            let area_delta = (new_shape_area - original_area).abs() / original_area;
129            if area_delta <= max_area_change_ratio {
130                debug!(
131                    "[PS] executed {:?} simplification causing {:.2}% area change",
132                    best_candidate,
133                    area_delta * 100.0
134                );
135                ref_points = new_shape;
136            } else {
137                break; //area change too significant
138            }
139        } else {
140            break; //no candidate found
141        }
142    }
143
144    //Convert it back to a simple polygon
145    let simpl_shape = SPolygon::new(ref_points).unwrap();
146
147    if simpl_shape.n_vertices() < shape.n_vertices() {
148        info!(
149            "[PS] simplified from {} to {} edges with {:.3}% area difference",
150            shape.n_vertices(),
151            simpl_shape.n_vertices(),
152            (simpl_shape.area - shape.area) / shape.area * 100.0
153        );
154    } else {
155        info!("[PS] no simplification possible within area change constraints");
156    }
157
158    simpl_shape
159}
160
161fn calculate_area_delta(shape: &[Point], candidate: &Candidate) -> Result<f32, InvalidCandidate> {
162    //calculate the difference in area of the shape if the candidate were to be executed
163    let area = match candidate {
164        Candidate::Collinear(_) => 0.0,
165        Candidate::Concave(c) => {
166            //Triangle formed by i_prev, i and i_next will correspond to the change area
167            let Point(x0, y0) = shape[c.0];
168            let Point(x1, y1) = shape[c.1];
169            let Point(x2, y2) = shape[c.2];
170
171            let area = (x0 * y1 + x1 * y2 + x2 * y0 - x0 * y2 - x1 * y0 - x2 * y1) / 2.0;
172
173            area.abs()
174        }
175        Candidate::ConvexConvex(c1, c2) => {
176            let replacing_vertex = replacing_vertex_convex_convex_candidate(shape, (*c1, *c2))?;
177
178            //the triangle formed by corner c1, c2, and replacing vertex will correspond to the change in area
179            let Point(x0, y0) = shape[c1.1];
180            let Point(x1, y1) = replacing_vertex;
181            let Point(x2, y2) = shape[c2.1];
182
183            let area = (x0 * y1 + x1 * y2 + x2 * y0 - x0 * y2 - x1 * y0 - x2 * y1) / 2.0;
184
185            area.abs()
186        }
187    };
188    Ok(area)
189}
190
191fn candidate_is_valid(shape: &[Point], candidate: &Candidate, bbox: &Rect) -> bool {
192    //ensure the removal/replacement does not create any self intersections, degenerate edges or grow the bounding box
193    match candidate {
194        Candidate::Collinear(_) => true,
195        Candidate::Concave(c) => {
196            let Ok(new_edge) = Edge::try_new(shape[c.0], shape[c.2]) else {
197                return false;
198            };
199            let affected_points = [shape[c.0], shape[c.1], shape[c.2]];
200
201            //check for self-intersections
202            edge_iter(shape)
203                .filter(|l| !affected_points.contains(&l.start))
204                .filter(|l| !affected_points.contains(&l.end))
205                .all(|l| !l.collides_with(&new_edge))
206        }
207        Candidate::ConvexConvex(c1, c2) => {
208            match replacing_vertex_convex_convex_candidate(shape, (*c1, *c2)) {
209                Err(_) => false,
210                //a replacing vertex outside the bounding box would make the shape larger in some dimension,
211                //which can prevent an item from fitting in a container it fits in originally
212                Ok(new_vertex) if !bbox.collides_with(&new_vertex) => false,
213                Ok(new_vertex) => {
214                    let (Ok(new_edge_1), Ok(new_edge_2)) = (
215                        Edge::try_new(shape[c1.0], new_vertex),
216                        Edge::try_new(new_vertex, shape[c2.2]),
217                    ) else {
218                        return false;
219                    };
220
221                    let affected_points = [shape[c1.1], shape[c1.0], shape[c2.1], shape[c2.2]];
222
223                    //check for self-intersections
224                    edge_iter(shape)
225                        .filter(|l| !affected_points.contains(&l.start))
226                        .filter(|l| !affected_points.contains(&l.end))
227                        .all(|l| !l.collides_with(&new_edge_1) && !l.collides_with(&new_edge_2))
228                }
229            }
230        }
231    }
232}
233
234//only used on points without short edges (see `simplify_shape`), so every edge is valid
235fn edge_iter(points: &[Point]) -> impl Iterator<Item = Edge> + '_ {
236    let n_points = points.len();
237    (0..n_points).map(move |i| {
238        let j = (i + 1) % n_points;
239        Edge::try_new(points[i], points[j]).unwrap()
240    })
241}
242
243fn execute_candidate(shape: &[Point], candidate: &Candidate) -> Vec<Point> {
244    let mut points = shape.iter().copied().collect_vec();
245    match candidate {
246        Candidate::Collinear(c) | Candidate::Concave(c) => {
247            points.remove(c.1);
248        }
249        Candidate::ConvexConvex(c1, c2) => {
250            let replacing_vertex = replacing_vertex_convex_convex_candidate(shape, (*c1, *c2))
251                .expect("invalid candidate cannot be executed");
252            points.remove(c1.1);
253            let other_index = if c1.1 < c2.1 { c2.1 - 1 } else { c2.1 };
254            points.remove(other_index);
255            points.insert(other_index, replacing_vertex);
256        }
257    }
258    points
259}
260
261fn replacing_vertex_convex_convex_candidate(
262    shape: &[Point],
263    (c1, c2): (Corner, Corner),
264) -> Result<Point, InvalidCandidate> {
265    assert_eq!(c1.2, c2.1, "non-consecutive corners {c1:?},{c2:?}");
266    assert_eq!(c1.1, c2.0, "non-consecutive corners {c1:?},{c2:?}");
267
268    let edge_prev = Edge::try_new(shape[c1.0], shape[c1.1]).unwrap();
269    let edge_next = Edge::try_new(shape[c2.2], shape[c2.1]).unwrap();
270
271    calculate_intersection_in_front(&edge_prev, &edge_next).ok_or(InvalidCandidate)
272}
273
274fn calculate_intersection_in_front(l1: &Edge, l2: &Edge) -> Option<Point> {
275    //Calculates the intersection point between l1 and l2 if both were extended in front to infinity.
276
277    //https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line_segment
278    //vector 1 = [(x1,y1),(x2,y2)[ and vector 2 = [(x3,y3),(x4,y4)[
279    let Point(x1, y1) = l1.start;
280    let Point(x2, y2) = l1.end;
281    let Point(x3, y3) = l2.start;
282    let Point(x4, y4) = l2.end;
283
284    //used formula is slightly different to the one on wikipedia. The orientation of the line segments are flipped
285    //We consider an intersection if t == ]0,1] && u == ]0,1]
286
287    let t_nom = (x2 - x4) * (y4 - y3) - (y2 - y4) * (x4 - x3);
288    let t_denom = (x2 - x1) * (y4 - y3) - (y2 - y1) * (x4 - x3);
289
290    let u_nom = (x2 - x4) * (y2 - y1) - (y2 - y4) * (x2 - x1);
291    let u_denom = (x2 - x1) * (y4 - y3) - (y2 - y1) * (x4 - x3);
292
293    let t = if t_denom == 0.0 { 0.0 } else { t_nom / t_denom };
294
295    let u = if u_denom == 0.0 { 0.0 } else { u_nom / u_denom };
296
297    if t < 0.0 && u < 0.0 {
298        //intersection is in front both vectors
299        Some(Point(x2 + t * (x1 - x2), y2 + t * (y1 - y2)))
300    } else {
301        //no intersection (parallel or not in front)
302        None
303    }
304}
305
306#[derive(Debug, Clone)]
307struct InvalidCandidate;
308
309#[derive(Clone, Debug, PartialEq)]
310enum Candidate {
311    Concave(Corner),
312    ConvexConvex(Corner, Corner),
313    Collinear(Corner),
314}
315
316#[derive(Clone, Copy, Debug, PartialEq)]
317///Corner is defined as the left hand side of points 0-1-2
318struct Corner(pub usize, pub usize, pub usize);
319
320impl Corner {
321    pub fn flip(&mut self) {
322        std::mem::swap(&mut self.0, &mut self.2);
323    }
324
325    pub fn to_points(self, points: &[Point]) -> [Point; 3] {
326        [points[self.0], points[self.1], points[self.2]]
327    }
328}
329
330#[derive(Clone, Copy, Debug, PartialEq)]
331enum CornerType {
332    Concave,
333    Convex,
334    Collinear,
335}
336
337impl CornerType {
338    pub fn from([p1, p2, p3]: [Point; 3]) -> Self {
339        //returns the corner type on the left-hand side p1->p2->p3
340        //From: https://algorithmtutor.com/Computational-Geometry/Determining-if-two-consecutive-segments-turn-left-or-right/
341
342        let p1p2 = (p2.0 - p1.0, p2.1 - p1.1);
343        let p1p3 = (p3.0 - p1.0, p3.1 - p1.1);
344        let cross_prod = p1p2.0 * p1p3.1 - p1p2.1 * p1p3.0;
345
346        //a positive cross product indicates that p2p3 turns to the left with respect to p1p2
347        match cross_prod.partial_cmp(&0.0).expect("cross product is NaN") {
348            Ordering::Less => CornerType::Concave,
349            Ordering::Equal => CornerType::Collinear,
350            Ordering::Greater => CornerType::Convex,
351        }
352    }
353}
354
355/// Extra distance by which [`offset_shape`] retries a failed offset, relative to the largest absolute coordinate of the shape.
356const OFFSET_RETRY_STEP: f32 = 1e-5;
357/// Number of retries in [`offset_shape`], each with ten times the extra distance of the previous one.
358const OFFSET_RETRIES: usize = 2;
359
360/// Offsets a [`SPolygon`] by a certain `distance` either inwards or outwards depending on the [`ShapeModifyMode`].
361/// Uses [`geo::Buffer`] to resolve intersections in the offset boundary.
362///
363/// The buffer is computed in `f64` and can contain zero-width spikes or pinches, for example where
364/// a slit is exactly twice the `distance` wide (see issue #130). Rounding it back to `f32` can make such
365/// a boundary self-intersect. In that case, the offset is retried with a slightly larger distance,
366/// which still yields a superset (inflate) or subset (deflate) of the original shape.
367pub fn offset_shape(sp: &SPolygon, mode: ShapeModifyMode, distance: f32) -> Result<SPolygon> {
368    let err = match offset_shape_once(sp, mode, distance) {
369        Ok(offset_sp) => return Ok(offset_sp),
370        Err(err) => err,
371    };
372
373    // f32 rounding errors scale with the magnitude of the coordinates
374    let Rect {
375        x_min,
376        y_min,
377        x_max,
378        y_max,
379    } = sp.bbox;
380    let coord_scale = [x_min, y_min, x_max, y_max]
381        .into_iter()
382        .map(f32::abs)
383        .fold(0.0, f32::max);
384    let mut extra = OFFSET_RETRY_STEP * coord_scale;
385    for _ in 0..OFFSET_RETRIES {
386        let retry_distance = distance + extra;
387        match offset_shape_once(sp, mode, retry_distance) {
388            Ok(offset_sp) => {
389                warn!(
390                    "[PS] offset by {distance} failed ({err}), offset by {retry_distance} instead"
391                );
392                return Ok(offset_sp);
393            }
394            Err(retry_err) => {
395                debug!("[PS] retried offset by {retry_distance} failed ({retry_err})");
396            }
397        }
398        extra *= 10.0;
399    }
400    Err(err)
401}
402
403fn offset_shape_once(sp: &SPolygon, mode: ShapeModifyMode, distance: f32) -> Result<SPolygon> {
404    let offset = match mode {
405        ShapeModifyMode::Deflate => -distance,
406        ShapeModifyMode::Inflate => distance,
407    };
408
409    // Convert the SPolygon to a geo_types::Polygon
410    let geo_poly = geo_types::Polygon::new(
411        sp.vertices
412            .iter()
413            .map(|p| (f64::from(p.0), f64::from(p.1)))
414            .collect(),
415        vec![],
416    );
417
418    // Create the offset polygon
419    // Preserve the previous buffer's 0.1-radian round-join resolution.
420    let style = BufferStyle::new(f64::from(offset)).line_join(LineJoin::Round(0.1));
421    let geo_poly_offsets = geo_poly.buffer_with_style(style).0;
422
423    let geo_poly_offset = match geo_poly_offsets.len() {
424        0 => bail!("Offset resulted in an empty polygon"),
425        1 => &geo_poly_offsets[0],
426        n => {
427            // The offset split the shape into disconnected parts (e.g. deflating past a narrow neck).
428            // Keep the largest part and drop the rest.
429            let areas = geo_poly_offsets
430                .iter()
431                .map(Area::unsigned_area)
432                .collect_vec();
433            let largest_idx = areas
434                .iter()
435                .position_max_by_key(|a| OrderedFloat(**a))
436                .unwrap();
437            let dropped_area = areas.iter().sum::<f64>() - areas[largest_idx];
438            error!(
439                "Offset split the shape into {n} disconnected parts, keeping the largest (area {:.3}) and dropping {} (total area {dropped_area:.3})",
440                areas[largest_idx],
441                n - 1
442            );
443            &geo_poly_offsets[largest_idx]
444        }
445    };
446
447    // Convert back to internal representation, without the closing point of geo's exterior ring.
448    // The buffer of f32 input stays well within f32 range.
449    #[allow(clippy::cast_possible_truncation)]
450    let mut points = geo_poly_offset
451        .exterior()
452        .points()
453        .map(|p| Point(p.x() as f32, p.y() as f32))
454        .collect_vec();
455    if points.len() > 1 && points.first() == points.last() {
456        points.pop();
457    }
458
459    SPolygon::new(points)
460}
461
462#[allow(clippy::too_many_lines)]
463/// Closes narrow concavities in a [`SPolygon`] by replacing them with a straight edge, eliminating the vertices in between.
464#[must_use]
465pub fn close_narrow_concavities(
466    orig_shape: &SPolygon,
467    mode: ShapeModifyMode,
468    (cutoff_distance_ratio, cutoff_area_ratio): (f32, f32),
469) -> SPolygon {
470    let mut n_concav_closed = 0;
471    let mut shape = orig_shape.clone();
472
473    for _ in 0..shape.n_vertices() {
474        let n_points = shape.n_vertices();
475
476        let calc_vert_elim = |i, j| {
477            if j > i {
478                j - i - 1
479            } else {
480                n_points - i + j - 1
481            }
482        };
483
484        let mut best_candidate = None;
485        for i in 0..n_points {
486            for j in 0..n_points {
487                if i == j || (i + 1) % n_points == j || (j + 1) % n_points == i {
488                    continue; //skip adjacent points
489                }
490                //Simulate the replacing edge
491                let c_edge = Edge::try_new(shape.vertex(i), shape.vertex(j))
492                    .expect("invalid edge in string candidate")
493                    .scale(0.9999); //slightly shrink the edge to avoid self-intersections
494
495                if c_edge.length() > cutoff_distance_ratio * shape.diameter {
496                    //If the edge is too long, skip it
497                    continue;
498                }
499
500                if c_edge.length() < SPolygon::MIN_EDGE_LENGTH_RATIO * shape.diameter {
501                    //If the edge is too short, SPolygon::new would remove one of its vertices, skip it
502                    continue;
503                }
504
505                if mode == ShapeModifyMode::Inflate
506                    && (shape.collides_with(&c_edge.start) || shape.collides_with(&c_edge.end))
507                {
508                    //If we are only allowed to inflate the shape and any end point is inside the shape, skip it
509                    continue;
510                }
511
512                if mode == ShapeModifyMode::Deflate
513                    && !(shape.collides_with(&c_edge.start) && shape.collides_with(&c_edge.end))
514                {
515                    //If we are only allowed to deflate the shape and both end points are not inside the shape, skip it
516                    continue;
517                }
518
519                if shape.edge_iter().any(|e| e.collides_with(&c_edge)) {
520                    //If the edge collides with any edge of the shape, reject always
521                    continue;
522                }
523                //the region cut off by the edge (from i to j, closed by the edge from j back to i)
524                //should have a negative area (in inflation mode) or positive area (in deflation mode)
525                let sub_shape_area = {
526                    let sub_shape_points = if j > i {
527                        shape.vertices[i..=j].to_vec()
528                    } else {
529                        [&shape.vertices[i..], &shape.vertices[..=j]].concat()
530                    };
531                    SPolygon::calculate_area(&sub_shape_points)
532                };
533                let wrong_side = match mode {
534                    ShapeModifyMode::Inflate => sub_shape_area >= 0.0,
535                    ShapeModifyMode::Deflate => sub_shape_area <= 0.0,
536                };
537                if wrong_side {
538                    //if the region lies on the wrong side of the edge, skip it
539                    continue;
540                }
541                if sub_shape_area.abs() > cutoff_area_ratio * shape.area {
542                    //if the area is too large, skip it
543                    continue;
544                }
545
546                //Valid candidate found...
547                match best_candidate {
548                    None => {
549                        //first candidate found
550                        best_candidate = Some((i, j));
551                    }
552                    Some((best_i, best_j)) => {
553                        //check the number of points that would be removed
554                        if calc_vert_elim(i, j) > calc_vert_elim(best_i, best_j) {
555                            best_candidate = Some((i, j));
556                        }
557                    }
558                }
559            }
560        }
561        if let Some((i, j)) = best_candidate {
562            let mut ref_points = shape.vertices.clone();
563            let start = i.cast_signed() + 1;
564            let end = j.cast_signed() - 1;
565            debug!(
566                "[PS] closing concavity between points (idx: {}, {:?}) and (idx: {}, {:?}) with edge length {:.3} ({} vertices eliminated)",
567                i,
568                shape.vertex(i),
569                j,
570                shape.vertex(j),
571                Edge::try_new(shape.vertex(i), shape.vertex(j))
572                    .expect("invalid edge in string candidate")
573                    .length(),
574                calc_vert_elim(i, j)
575            );
576            if start <= end {
577                // if j does not wrap around the shape
578                ref_points.drain(start.cast_unsigned()..=end.cast_unsigned());
579            } else {
580                // if j wraps around the shape
581                if start.cast_unsigned() < n_points {
582                    //remove from `start` to back
583                    ref_points.drain(start.cast_unsigned()..);
584                }
585                if end >= 0 {
586                    //remove from front to `end`
587                    ref_points.drain(0..=end.cast_unsigned());
588                }
589            }
590            shape = SPolygon::new(ref_points).expect("invalid shape after closing concavity");
591            n_concav_closed += 1;
592        } else {
593            //no more candidates found, break the loop
594            break;
595        }
596    }
597
598    if n_concav_closed > 0 {
599        info!(
600            "[PS] [EXPERIMENTAL] closed {} concavities closer than {:.3}% of diameter and less than {:.3}% of area, reducing vertices from {} to {}",
601            n_concav_closed,
602            cutoff_distance_ratio * 100.0,
603            cutoff_area_ratio * 100.0,
604            orig_shape.n_vertices(),
605            shape.n_vertices()
606        );
607    }
608
609    shape
610}
611
612#[must_use]
613pub fn shape_modification_valid(orig: &SPolygon, simpl: &SPolygon, mode: ShapeModifyMode) -> bool {
614    //make sure each point of the original shape is either in the new shape or included (in case of inflation)/excluded (in case of deflation) in the new shape
615    let on_edge = |p: &Point| {
616        simpl
617            .edge_iter()
618            .any(|e| e.distance_to(p) < simpl.diameter * 1e-6)
619    };
620
621    for p in orig.vertices.iter().filter(|p| !simpl.vertices.contains(p)) {
622        let vertex_on_edge = on_edge(p);
623        let vertex_in_simpl = simpl.collides_with(p);
624
625        let error = match mode {
626            ShapeModifyMode::Inflate => !vertex_in_simpl && !vertex_on_edge,
627            ShapeModifyMode::Deflate => vertex_in_simpl && !vertex_on_edge,
628        };
629
630        if error {
631            error!(
632                "[PS] point {:?} from original shape is incorrect in simplified shape (original vertices: {:?}, simplified vertices: {:?})",
633                p,
634                orig.vertices.iter().map(|p| (p.0, p.1)).collect_vec(),
635                simpl.vertices.iter().map(|p| (p.0, p.1)).collect_vec()
636            );
637            return false; //point is not in the new shape and does not collide with it
638        }
639    }
640    true
641}