geometry_algorithm/remove_spikes.rs
1//! `remove_spikes(&mut g)` — drop collinear-and-reversed vertices.
2//!
3//! Mirrors `boost::geometry::remove_spikes` from
4//! `boost/geometry/algorithms/remove_spikes.hpp`. The predicate is
5//! Boost's `point_is_spike_or_equal`, and the `or_equal` half carries
6//! its weight: a triple `(a, b, c)` qualifies when `(b-a) × (c-b) == 0`
7//! (collinear) and `(b-a) · (c-b) <= 0`, which covers both a reversal
8//! and a zero-length step — that is, a repeated vertex. The middle
9//! vertex `b` is removed; the walk repeats until nothing qualifies,
10//! because collapsing one spike can create a new one at the
11//! now-adjacent pair, and peeling a spike off a ring routinely leaves a
12//! repeated vertex behind.
13//!
14//! Per-kind:
15//! * `Linestring`, `Ring` → spike-walk the backing `Vec<P>`
16//! * `Polygon` → walk outer + every inner ring
17//! * `MultiPolygon` → walk each member
18//!
19//! Cartesian-only: the collinearity / reversal predicate is the 2D
20//! cross/dot product. Spherical / geographic spike detection needs
21//! angle-aware predicates; deferred until a downstream caller appears.
22
23use geometry_coords::CoordinateScalar;
24use geometry_model::{Linestring, MultiPolygon, Polygon, Ring};
25use geometry_trait::Point as PointTrait;
26
27/// Remove spikes from `g` in place.
28///
29/// Mirrors `boost::geometry::remove_spikes(g)` from
30/// `boost/geometry/algorithms/remove_spikes.hpp`.
31pub fn remove_spikes<G: RemoveSpikes>(g: &mut G) {
32 g.remove_spikes();
33}
34
35/// Per-kind spike-removal dispatch.
36#[doc(hidden)]
37pub trait RemoveSpikes {
38 fn remove_spikes(&mut self);
39}
40
41/// True iff `b` is a spike between `a` and `c`, **or** duplicates one of
42/// them: 2D cross `== 0` and dot `<= 0`.
43///
44/// Mirrors `detail::point_is_spike_or_equal`
45/// (`algorithms/detail/point_is_spike_or_equal.hpp`). Requiring `dot < 0`
46/// instead would leave every repeated vertex in place, including the ones
47/// this function creates: removing the apex of `(4,0) (6,0) (4,0)` leaves
48/// `(4,0) (4,0)` adjacent, and Boost collapses that.
49///
50/// `dot <= 0` cannot over-match. Two non-zero vectors that are both
51/// parallel (`cross == 0`) and perpendicular (`dot == 0`) do not exist, so
52/// the equality arm fires only when one of the steps has zero length.
53fn is_spike_or_equal_2d<P: PointTrait>(a: &P, b: &P, c: &P) -> bool {
54 let ux = b.get::<0>() - a.get::<0>();
55 let uy = b.get::<1>() - a.get::<1>();
56 let vx = c.get::<0>() - b.get::<0>();
57 let vy = c.get::<1>() - b.get::<1>();
58 let cross = ux * vy - uy * vx;
59 let dot = ux * vx + uy * vy;
60 let zero = <P::Scalar as CoordinateScalar>::ZERO;
61 // The collinearity half is Boost's `side_by_triangle`, which calls three
62 // points collinear whenever any *two* of them are equal by `math::equals`
63 // — a relative epsilon — before it looks at any determinant
64 // (`side_by_triangle.hpp:150-164`). A hairline whose two ends are a few
65 // last bits apart at a large coordinate is a spike to Boost and a genuine
66 // sliver to an exact cross product, which is how one survived into a tile
67 // that the reference drew as nothing.
68 let same = |ax: P::Scalar, ay: P::Scalar, bx: P::Scalar, by: P::Scalar| {
69 ax.tolerant_eq(bx) && ay.tolerant_eq(by)
70 };
71 let collinear = cross == zero
72 || same(a.get::<0>(), a.get::<1>(), b.get::<0>(), b.get::<1>())
73 || same(a.get::<0>(), a.get::<1>(), c.get::<0>(), c.get::<1>())
74 || same(b.get::<0>(), b.get::<1>(), c.get::<0>(), c.get::<1>());
75 collinear && dot <= zero
76}
77
78fn walk_spikes<P: PointTrait>(pts: &mut alloc::vec::Vec<P>) {
79 let mut changed = true;
80 while changed && pts.len() >= 3 {
81 changed = false;
82 let mut i = 1;
83 while i + 1 < pts.len() {
84 if is_spike_or_equal_2d(&pts[i - 1], &pts[i], &pts[i + 1]) {
85 pts.remove(i);
86 changed = true;
87 // Do not advance `i`: the new `pts[i]` (was `pts[i+1]`)
88 // may now form a spike with `pts[i-1]`.
89 if i > 1 {
90 i -= 1;
91 }
92 } else {
93 i += 1;
94 }
95 }
96 }
97}
98
99impl<P: PointTrait> RemoveSpikes for Linestring<P> {
100 fn remove_spikes(&mut self) {
101 walk_spikes(&mut self.0);
102 }
103}
104
105/// Spike-walk a **ring**: the interior linear pass plus the wrap-around
106/// seam that a linestring does not have.
107///
108/// Mirrors `detail::remove_spikes::range_remove_spikes::apply`
109/// (`algorithms/remove_spikes.hpp:99-141`). After the interior pass,
110/// Boost drops the closing point of a closed ring, then repeatedly
111/// removes a spike formed at the *first* vertex — the triple
112/// `(back-1, back, front)` — and at the *second* — `(back, front,
113/// front+1)` — until neither fires, and re-adds the closing point. The
114/// interior [`walk_spikes`] alone never forms those seam triples, so a
115/// spike sitting on the ring's first/last vertex would otherwise survive.
116///
117/// `closed` is `true` when the backing vector repeats its first vertex as
118/// its last (the model's `CLOSED` const generic).
119fn walk_ring_spikes<P: PointTrait + Copy>(pts: &mut alloc::vec::Vec<P>, closed: bool) {
120 // Interior pass first.
121 walk_spikes(pts);
122
123 // Work on the open sequence: drop the duplicated closing vertex, if
124 // any, so `first` and `last` are distinct ring vertices.
125 let had_closing = closed && pts.len() >= 2 && same_point(&pts[0], &pts[pts.len() - 1]);
126 if had_closing {
127 pts.pop();
128 }
129
130 // Seam cleanup: alternately peel a spike off the back (last vertex)
131 // and the front (first vertex) until the seam is clean.
132 let mut found = true;
133 while found {
134 found = false;
135 // Spike at the first point: (prev = back-1, back, front).
136 while pts.len() >= 3
137 && is_spike_or_equal_2d(&pts[pts.len() - 2], &pts[pts.len() - 1], &pts[0])
138 {
139 pts.pop();
140 found = true;
141 }
142 // Spike at the second point: (back, front, front+1).
143 while pts.len() >= 3 && is_spike_or_equal_2d(&pts[pts.len() - 1], &pts[0], &pts[1]) {
144 pts.remove(0);
145 found = true;
146 }
147 }
148
149 // Re-add the closing vertex we removed, restoring the ring's closure.
150 if had_closing && !pts.is_empty() {
151 let first = pts[0];
152 pts.push(first);
153 }
154}
155
156/// Coordinate equality of two points (2D).
157fn same_point<P: PointTrait>(a: &P, b: &P) -> bool {
158 a.get::<0>() == b.get::<0>() && a.get::<1>() == b.get::<1>()
159}
160
161impl<P: PointTrait + Copy, const CW: bool, const CL: bool> RemoveSpikes for Ring<P, CW, CL> {
162 fn remove_spikes(&mut self) {
163 walk_ring_spikes(&mut self.0, CL);
164 }
165}
166
167impl<P: PointTrait + Copy, const CW: bool, const CL: bool> RemoveSpikes for Polygon<P, CW, CL> {
168 fn remove_spikes(&mut self) {
169 walk_ring_spikes(&mut self.outer.0, CL);
170 for inner in &mut self.inners {
171 walk_ring_spikes(&mut inner.0, CL);
172 }
173 }
174}
175
176impl<Pg: RemoveSpikes + geometry_trait::Polygon> RemoveSpikes for MultiPolygon<Pg> {
177 fn remove_spikes(&mut self) {
178 for p in &mut self.0 {
179 p.remove_spikes();
180 }
181 }
182}
183
184#[cfg(test)]
185mod tests {
186 //! Reference behaviour from
187 //! `boost/geometry/test/algorithms/remove_spikes.cpp`: an
188 //! out-and-back spur on a linestring is collapsed to its base
189 //! vertex.
190
191 use super::remove_spikes;
192 use geometry_cs::Cartesian;
193 use geometry_model::{Point2D, Ring, linestring};
194 use geometry_trait::{Linestring as _, Point as _, Ring as _};
195
196 type P = Point2D<f64, Cartesian>;
197
198 fn spike_ring(points: &[(f64, f64)]) -> Ring<P> {
199 let mut ring = Ring::new();
200 for &(x, y) in points {
201 ring.push(P::new(x, y));
202 }
203 ring
204 }
205
206 /// A hairline whose two ends are four last bits apart at a coordinate of
207 /// 3540, which is inside one epsilon of it.
208 ///
209 /// C++: `side_by_triangle` calls three points collinear when any two of
210 /// them are `math::equals` — a *relative* epsilon — before it computes any
211 /// determinant, so Boost sees a spike here and collapses the ring to a
212 /// single repeated point. An exact cross product sees a sliver with real
213 /// area and keeps it, which is how one survived into a monaco tile the
214 /// reference drew as nothing.
215 #[test]
216 fn a_hairline_within_an_epsilon_is_a_spike() {
217 let mut ring = spike_ring(&[
218 (3_539.999_999_999_999_5, 482.199_999_999_999_76),
219 (3540.0, 482.199_999_999_999_8),
220 (3540.0, 479.0),
221 (3_539.999_999_999_999_5, 482.199_999_999_999_76),
222 ]);
223 remove_spikes(&mut ring);
224 assert_eq!(ring.0.len(), 2, "{:?}", ring.0);
225 }
226
227 /// The same ring with its two ends far enough apart to be two points,
228 /// where the sliver has real area and stays.
229 #[test]
230 fn a_sliver_wider_than_an_epsilon_is_kept() {
231 let mut ring = spike_ring(&[
232 (3_539.999_999_9, 482.199_999_9),
233 (3540.0, 482.2),
234 (3540.0, 479.0),
235 (3_539.999_999_9, 482.199_999_9),
236 ]);
237 remove_spikes(&mut ring);
238 assert_eq!(ring.0.len(), 4, "{:?}", ring.0);
239 }
240
241 #[test]
242 fn out_and_back_spur_is_removed() {
243 // (0,0) → (1,0) → (3,0) → (2,0): the tip (3,0) is a reversed
244 // collinear overshoot between (1,0) and (2,0), so it is dropped,
245 // leaving the monotone run (0,0) → (1,0) → (2,0).
246 let mut ls: geometry_model::Linestring<P> =
247 linestring![(0.0, 0.0), (1.0, 0.0), (3.0, 0.0), (2.0, 0.0)];
248 remove_spikes(&mut ls);
249 let xs: Vec<f64> = ls.points().map(geometry_trait::Point::get::<0>).collect();
250 assert_eq!(xs, vec![0.0, 1.0, 2.0]);
251 }
252
253 #[test]
254 fn spike_free_linestring_is_unchanged() {
255 let mut ls: geometry_model::Linestring<P> = linestring![(0.0, 0.0), (1.0, 1.0), (2.0, 0.0)];
256 remove_spikes(&mut ls);
257 assert_eq!(ls.points().count(), 3);
258 }
259
260 /// A cascading spike: removing the inner tip exposes a second spike
261 /// at the now-adjacent pair, which the non-advancing backtrack
262 /// (`i -= 1`) then also removes. All overshoots collapse to the base
263 /// monotone run.
264 #[test]
265 fn cascading_spikes_all_collapse() {
266 // (0,0) → (2,0) → (5,0) → (3,0) → (1,0): both (5,0) and the
267 // resulting reversed vertices are collinear overshoots along the
268 // x-axis. After the walk only a monotone sequence survives.
269 let mut ls: geometry_model::Linestring<P> =
270 linestring![(0.0, 0.0), (2.0, 0.0), (5.0, 0.0), (3.0, 0.0), (1.0, 0.0)];
271 remove_spikes(&mut ls);
272 let xs: Vec<f64> = ls.points().map(geometry_trait::Point::get::<0>).collect();
273 assert_eq!(xs, vec![0.0, 1.0]);
274 }
275
276 /// A `Polygon` removes spikes from its exterior *and* every interior
277 /// ring.
278 #[test]
279 fn polygon_removes_spikes_in_outer_and_holes() {
280 use geometry_model::{Polygon, Ring};
281 use geometry_trait::{Point as _, Polygon as _, Ring as _};
282 // Outer square with a spur vertex (5,0) on the bottom edge.
283 let outer = Ring::from_vec(vec![
284 P::new(0.0, 0.0),
285 P::new(4.0, 0.0),
286 P::new(5.0, 0.0), // reversed-collinear overshoot then back
287 P::new(4.0, 0.0),
288 P::new(4.0, 4.0),
289 P::new(0.0, 4.0),
290 P::new(0.0, 0.0),
291 ]);
292 // Hole with its own spur.
293 let hole = Ring::from_vec(vec![
294 P::new(1.0, 1.0),
295 P::new(2.0, 1.0),
296 P::new(3.0, 1.0), // overshoot
297 P::new(2.0, 1.0),
298 P::new(2.0, 2.0),
299 P::new(1.0, 1.0),
300 ]);
301 let mut pg: Polygon<P> = Polygon::with_inners(outer, vec![hole]);
302 remove_spikes(&mut pg);
303 // The (5,0) and (3,1) overshoot vertices are gone.
304 let ext: Vec<(f64, f64)> = pg
305 .exterior()
306 .points()
307 .map(|p| (p.get::<0>(), p.get::<1>()))
308 .collect();
309 assert!(!ext.contains(&(5.0, 0.0)), "outer spike survived: {ext:?}");
310 let hole_pts: Vec<(f64, f64)> = pg
311 .interiors()
312 .next()
313 .unwrap()
314 .points()
315 .map(|p| (p.get::<0>(), p.get::<1>()))
316 .collect();
317 assert!(!hole_pts.contains(&(3.0, 1.0)), "hole spike survived");
318 }
319
320 /// A `MultiPolygon` removes spikes from each member polygon.
321 #[test]
322 fn multipolygon_removes_spikes_from_each_member() {
323 use geometry_model::{MultiPolygon, Polygon, Ring};
324 use geometry_trait::{Point as _, Polygon as _, Ring as _};
325 let spiky = || {
326 Polygon::<P>::new(Ring::from_vec(vec![
327 P::new(0.0, 0.0),
328 P::new(4.0, 0.0),
329 P::new(5.0, 0.0),
330 P::new(4.0, 0.0),
331 P::new(4.0, 4.0),
332 P::new(0.0, 4.0),
333 P::new(0.0, 0.0),
334 ]))
335 };
336 let mut mpg: MultiPolygon<Polygon<P>> = MultiPolygon(vec![spiky(), spiky()]);
337 remove_spikes(&mut mpg);
338 for pg in &mpg.0 {
339 let pts: Vec<(f64, f64)> = pg
340 .exterior()
341 .points()
342 .map(|p| (p.get::<0>(), p.get::<1>()))
343 .collect();
344 assert!(!pts.contains(&(5.0, 0.0)), "member spike survived");
345 }
346 }
347
348 #[test]
349 fn ring_seam_spike_is_removed() {
350 // A closed ring whose FIRST vertex is a reversed-collinear spike
351 // straddling the seam — a triple the interior pass never inspects.
352 // Vertices: (0,0)[seam], (2,0), (2,2), (0,2), (1,0), close(0,0).
353 // Dropping the closing duplicate leaves the open loop
354 // [(0,0), (2,0), (2,2), (0,2), (1,0)].
355 // Seam triple at the first vertex is (back=(1,0), front=(0,0),
356 // front+1=(2,0)): u=(0,0)−(1,0)=(−1,0), v=(2,0)−(0,0)=(2,0),
357 // cross=0 and dot=−2<0 → a spike at (0,0). Boost removes it; the
358 // wrap-around seam cleanup must too.
359 use geometry_model::Ring;
360 use geometry_trait::{Point as _, Ring as _};
361
362 let mut r: Ring<P> = Ring::from_vec(vec![
363 P::new(0.0, 0.0),
364 P::new(2.0, 0.0),
365 P::new(2.0, 2.0),
366 P::new(0.0, 2.0),
367 P::new(1.0, 0.0),
368 P::new(0.0, 0.0),
369 ]);
370 remove_spikes(&mut r);
371
372 let pts: Vec<(f64, f64)> = r.points().map(|p| (p.get::<0>(), p.get::<1>())).collect();
373 // The seam spike vertex (0,0) was dropped.
374 assert!(
375 !pts.contains(&(0.0, 0.0)),
376 "seam spike vertex (0,0) must be gone: {pts:?}"
377 );
378 // Ring stays closed and non-degenerate.
379 assert!(r.points().count() >= 4);
380 assert_eq!(pts.first(), pts.last(), "ring must remain closed");
381 }
382
383 /// Boost collapses a repeated vertex the same way it collapses a
384 /// spike — `point_is_spike_or_equal` covers both. Expected values from
385 /// `boost::geometry::remove_spikes` on a clockwise `model::polygon`
386 /// (Boost 1.83):
387 ///
388 /// ```text
389 /// consecutive dup -> (0,0) (0,4) (4,4) (4,0) (0,0)
390 /// dup at start -> (0,0) (0,4) (4,4) (4,0) (0,0)
391 /// triple dup -> (0,0) (0,4) (4,4) (4,0) (0,0)
392 /// real spike -> (0,0) (0,4) (4,4) (4,0) (0,0)
393 /// dup + spike -> (0,0) (0,4) (4,4) (4,0) (0,0)
394 /// ```
395 ///
396 /// The `real spike` row is the one that shows why: removing the apex
397 /// of `(4,0) (6,0) (4,0)` leaves `(4,0) (4,0)` adjacent, so a
398 /// spike-only predicate makes duplicates out of its own output.
399 #[test]
400 fn repeated_vertices_are_collapsed() {
401 let square = [(0.0, 0.0), (0.0, 4.0), (4.0, 4.0), (4.0, 0.0), (0.0, 0.0)];
402
403 for (name, input) in [
404 (
405 "consecutive dup",
406 vec![
407 (0.0, 0.0),
408 (0.0, 4.0),
409 (4.0, 4.0),
410 (4.0, 4.0),
411 (4.0, 0.0),
412 (0.0, 0.0),
413 ],
414 ),
415 (
416 "dup at start",
417 vec![
418 (0.0, 0.0),
419 (0.0, 0.0),
420 (0.0, 4.0),
421 (4.0, 4.0),
422 (4.0, 0.0),
423 (0.0, 0.0),
424 ],
425 ),
426 (
427 "triple dup",
428 vec![
429 (0.0, 0.0),
430 (0.0, 4.0),
431 (4.0, 4.0),
432 (4.0, 4.0),
433 (4.0, 4.0),
434 (4.0, 0.0),
435 (0.0, 0.0),
436 ],
437 ),
438 (
439 "real spike",
440 vec![
441 (0.0, 0.0),
442 (0.0, 4.0),
443 (4.0, 4.0),
444 (4.0, 0.0),
445 (6.0, 0.0),
446 (4.0, 0.0),
447 (0.0, 0.0),
448 ],
449 ),
450 (
451 "dup + spike",
452 vec![
453 (0.0, 0.0),
454 (0.0, 4.0),
455 (4.0, 4.0),
456 (4.0, 4.0),
457 (4.0, 0.0),
458 (6.0, 0.0),
459 (4.0, 0.0),
460 (0.0, 0.0),
461 ],
462 ),
463 ] {
464 let mut ring: Ring<P> =
465 Ring::from_vec(input.iter().map(|&(x, y)| P::new(x, y)).collect());
466 remove_spikes(&mut ring);
467 let pts: Vec<(f64, f64)> = ring
468 .points()
469 .map(|p| (p.get::<0>(), p.get::<1>()))
470 .collect();
471 assert_eq!(pts, square, "{name}");
472 }
473 }
474}