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#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]
22pub enum ShapeModifyMode {
23 Inflate,
25 Deflate,
27}
28
29#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq)]
30pub struct ShapeModifyConfig {
32 pub simplify_tolerance: Option<f32>,
36 pub offset: Option<f32>,
40 pub narrow_concavity_cutoff: Option<(f32, f32)>,
48}
49
50pub 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 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 corners.reverse();
88 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 for corner in &corners {
99 let corner_type = CornerType::from(corner.to_points(&ref_points));
100
101 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 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 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; }
139 } else {
140 break; }
142 }
143
144 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 let area = match candidate {
164 Candidate::Collinear(_) => 0.0,
165 Candidate::Concave(c) => {
166 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 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 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 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 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 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
234fn 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 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 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 Some(Point(x2 + t * (x1 - x2), y2 + t * (y1 - y2)))
300 } else {
301 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)]
317struct 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 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 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
355const OFFSET_RETRY_STEP: f32 = 1e-5;
357const OFFSET_RETRIES: usize = 2;
359
360pub 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 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 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 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 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 #[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#[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; }
490 let c_edge = Edge::try_new(shape.vertex(i), shape.vertex(j))
492 .expect("invalid edge in string candidate")
493 .scale(0.9999); if c_edge.length() > cutoff_distance_ratio * shape.diameter {
496 continue;
498 }
499
500 if c_edge.length() < SPolygon::MIN_EDGE_LENGTH_RATIO * shape.diameter {
501 continue;
503 }
504
505 if mode == ShapeModifyMode::Inflate
506 && (shape.collides_with(&c_edge.start) || shape.collides_with(&c_edge.end))
507 {
508 continue;
510 }
511
512 if mode == ShapeModifyMode::Deflate
513 && !(shape.collides_with(&c_edge.start) && shape.collides_with(&c_edge.end))
514 {
515 continue;
517 }
518
519 if shape.edge_iter().any(|e| e.collides_with(&c_edge)) {
520 continue;
522 }
523 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 continue;
540 }
541 if sub_shape_area.abs() > cutoff_area_ratio * shape.area {
542 continue;
544 }
545
546 match best_candidate {
548 None => {
549 best_candidate = Some((i, j));
551 }
552 Some((best_i, best_j)) => {
553 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 ref_points.drain(start.cast_unsigned()..=end.cast_unsigned());
579 } else {
580 if start.cast_unsigned() < n_points {
582 ref_points.drain(start.cast_unsigned()..);
584 }
585 if end >= 0 {
586 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 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 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; }
639 }
640 true
641}