surfer2 0.1.0

Headless straight-skeleton engine: a source-derived Rust port of cgalab/surfer2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Input models: general PSLG and polygon-with-holes façade.
//!
//! Upstream: `surf/src/BasicInput.*`, GraphML vertex/edge loading in `BGLGraph.*`.
//! Additive edge weights from GraphML are intentionally omitted (upstream never
//! applies them to propagation).

use crate::error::InputError;
use crate::geometry::{require_finite_point, segments_properly_intersect, Point2};

/// Undirected input constraint with multiplicative positive weight.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct InputEdge {
    pub vertices: [usize; 2],
    pub weight: f64,
}

impl InputEdge {
    pub fn new(v0: usize, v1: usize, weight: f64) -> Self {
        Self {
            vertices: [v0, v1],
            weight,
        }
    }

    #[inline]
    pub fn normalized_endpoints(self) -> (usize, usize) {
        let a = self.vertices[0];
        let b = self.vertices[1];
        if a <= b {
            (a, b)
        } else {
            (b, a)
        }
    }
}

/// Planar straight-line graph accepted by the general skeleton API.
#[derive(Debug, Clone, PartialEq)]
pub struct Pslg {
    vertices: Vec<Point2>,
    edges: Vec<InputEdge>,
}

impl Pslg {
    pub fn new(vertices: Vec<Point2>, edges: Vec<InputEdge>) -> Result<Self, InputError> {
        validate_pslg(&vertices, &edges)?;
        Ok(Self { vertices, edges })
    }

    /// Already-validated clone; `Polygon::new` already ran `validate_pslg`.
    pub(crate) fn from_validated(vertices: Vec<Point2>, edges: Vec<InputEdge>) -> Self {
        Self { vertices, edges }
    }

    pub fn from_flat(
        xy: &[[f64; 2]],
        edge_vertices: &[[usize; 2]],
        weights: Option<&[f64]>,
    ) -> Result<Self, InputError> {
        if xy.is_empty() {
            return Err(InputError::Empty);
        }
        let vertices: Vec<Point2> = xy.iter().copied().map(Point2::from_array).collect();
        let edges = match weights {
            None => edge_vertices
                .iter()
                .map(|e| InputEdge::new(e[0], e[1], 1.0))
                .collect(),
            Some(w) => {
                if w.len() != edge_vertices.len() {
                    return Err(InputError::Empty);
                }
                edge_vertices
                    .iter()
                    .zip(w.iter())
                    .map(|(e, &weight)| InputEdge::new(e[0], e[1], weight))
                    .collect()
            }
        };
        Self::new(vertices, edges)
    }

    #[inline]
    pub fn vertices(&self) -> &[Point2] {
        &self.vertices
    }

    #[inline]
    pub fn edges(&self) -> &[InputEdge] {
        &self.edges
    }

    #[inline]
    pub fn vertex_count(&self) -> usize {
        self.vertices.len()
    }

    #[inline]
    pub fn edge_count(&self) -> usize {
        self.edges.len()
    }
}

/// Polygon with optional holes. Ring winding is ignored; interior is the
/// odd-parity region of the constraint arrangement.
#[derive(Debug, Clone, PartialEq)]
pub struct Polygon {
    /// All vertices in order: exterior then holes.
    vertices: Vec<Point2>,
    /// Edge list derived from rings (closed, last→first).
    edges: Vec<InputEdge>,
    /// `ring_offsets[i]` = start vertex index of ring i; final sentinel = vertex count.
    ring_offsets: Vec<usize>,
}

impl Polygon {
    pub fn new(exterior: Vec<Point2>, holes: Vec<Vec<Point2>>) -> Result<Self, InputError> {
        let mut rings = Vec::with_capacity(1 + holes.len());
        rings.push(exterior);
        rings.extend(holes);
        from_rings(rings)
    }

    /// Flat coordinates with ring start offsets. `ring_offsets` must include a
    /// trailing sentinel equal to `xy.len()`, or omit it (inferred).
    pub fn from_flat(xy: &[[f64; 2]], ring_offsets: &[usize]) -> Result<Self, InputError> {
        if xy.is_empty() || ring_offsets.is_empty() {
            return Err(InputError::Empty);
        }
        let mut offsets: Vec<usize> = ring_offsets.to_vec();
        if *offsets.last().unwrap() != xy.len() {
            offsets.push(xy.len());
        }
        if offsets[0] != 0 {
            return Err(InputError::Empty);
        }
        for w in offsets.windows(2) {
            if w[1] < w[0] {
                return Err(InputError::Empty);
            }
        }
        let mut rings = Vec::with_capacity(offsets.len() - 1);
        for w in offsets.windows(2) {
            let ring: Vec<Point2> = xy[w[0]..w[1]]
                .iter()
                .copied()
                .map(Point2::from_array)
                .collect();
            rings.push(ring);
        }
        from_rings(rings)
    }

    #[inline]
    pub fn vertices(&self) -> &[Point2] {
        &self.vertices
    }

    #[inline]
    pub fn edges(&self) -> &[InputEdge] {
        &self.edges
    }

    #[inline]
    pub fn ring_offsets(&self) -> &[usize] {
        &self.ring_offsets
    }

    #[inline]
    pub fn ring_count(&self) -> usize {
        self.ring_offsets.len().saturating_sub(1)
    }

    #[inline]
    pub fn hole_count(&self) -> usize {
        self.ring_count().saturating_sub(1)
    }

    /// View as a PSLG (shared topology; weight 1 on every edge).
    pub fn as_pslg(&self) -> Result<Pslg, InputError> {
        Ok(Pslg::from_validated(
            self.vertices.clone(),
            self.edges.clone(),
        ))
    }
}

fn from_rings(mut rings: Vec<Vec<Point2>>) -> Result<Polygon, InputError> {
    if rings.is_empty() {
        return Err(InputError::Empty);
    }
    for (ri, ring) in rings.iter_mut().enumerate() {
        strip_closing_duplicate(ring);
        if ring.len() < 3 {
            return Err(InputError::RingTooSmall { ring: ri });
        }
        for (i, p) in ring.iter().enumerate() {
            require_finite_point(*p, i)?;
        }
        for i in 0..ring.len() {
            let j = (i + 1) % ring.len();
            if ring[i] == ring[j] {
                return Err(InputError::DuplicateConsecutiveVertices {
                    ring: ri,
                    offset: i,
                });
            }
        }
    }

    let mut vertices = Vec::new();
    let mut edges = Vec::new();
    let mut ring_offsets = Vec::with_capacity(rings.len() + 1);
    ring_offsets.push(0);

    for ring in &rings {
        let base = vertices.len();
        let n = ring.len();
        vertices.extend_from_slice(ring);
        for i in 0..n {
            let v0 = base + i;
            let v1 = base + ((i + 1) % n);
            edges.push(InputEdge::new(v0, v1, 1.0));
        }
        ring_offsets.push(vertices.len());
    }

    validate_pslg(&vertices, &edges)?;
    // Additional ring nesting checks: holes must lie inside exterior via
    // point-in-polygon on their first vertex (strict for non-touching contract).
    if rings.len() > 1 {
        let exterior = &rings[0];
        for (hi, hole) in rings.iter().enumerate().skip(1) {
            let probe = hole[0];
            if !point_in_ring_odd_even(probe, exterior) {
                return Err(InputError::HoleOutsideExterior { hole: hi - 1 });
            }
            // Hole must not contain exterior vertices (crude nesting sanity).
            if point_in_ring_odd_even(exterior[0], hole) {
                return Err(InputError::HoleOutsideExterior { hole: hi - 1 });
            }
        }
    }

    Ok(Polygon {
        vertices,
        edges,
        ring_offsets,
    })
}

fn strip_closing_duplicate(ring: &mut Vec<Point2>) {
    if ring.len() >= 2 {
        let first = ring[0];
        let last = *ring.last().unwrap();
        if first == last {
            ring.pop();
        }
    }
}

fn validate_pslg(vertices: &[Point2], edges: &[InputEdge]) -> Result<(), InputError> {
    if vertices.is_empty() {
        return Err(InputError::Empty);
    }
    for (i, p) in vertices.iter().enumerate() {
        require_finite_point(*p, i)?;
    }
    let n = vertices.len();
    let mut seen = std::collections::BTreeSet::new();
    for (ei, e) in edges.iter().enumerate() {
        let v0 = e.vertices[0];
        let v1 = e.vertices[1];
        if v0 >= n || v1 >= n {
            return Err(InputError::VertexIndexOutOfRange {
                index: v0.max(v1),
                vertex_count: n,
            });
        }
        if v0 == v1 || vertices[v0] == vertices[v1] {
            return Err(InputError::ZeroLengthEdge { edge: ei, v0, v1 });
        }
        if !(e.weight.is_finite() && e.weight > 0.0) {
            return Err(InputError::NonPositiveWeight {
                edge: ei,
                weight: e.weight,
            });
        }
        let key = e.normalized_endpoints();
        if !seen.insert(key) {
            return Err(InputError::DuplicateEdge {
                v0: key.0,
                v1: key.1,
            });
        }
    }

    // Proper crossings between non-adjacent edges.
    for i in 0..edges.len() {
        let a0 = vertices[edges[i].vertices[0]];
        let a1 = vertices[edges[i].vertices[1]];
        let ia = edges[i].normalized_endpoints();
        for j in (i + 1)..edges.len() {
            let ib = edges[j].normalized_endpoints();
            // Share a vertex → adjacent or incident; not a proper crossing.
            if ia.0 == ib.0 || ia.0 == ib.1 || ia.1 == ib.0 || ia.1 == ib.1 {
                continue;
            }
            let b0 = vertices[edges[j].vertices[0]];
            let b1 = vertices[edges[j].vertices[1]];
            if segments_properly_intersect(a0, a1, b0, b1) {
                return Err(InputError::CrossingConstraints { e0: i, e1: j });
            }
        }
    }
    Ok(())
}

/// Odd-even fill rule; boundary counts as outside for hole nesting probes.
fn point_in_ring_odd_even(p: Point2, ring: &[Point2]) -> bool {
    let mut inside = false;
    let n = ring.len();
    if n < 3 {
        return false;
    }
    let mut j = n - 1;
    for i in 0..n {
        let pi = ring[i];
        let pj = ring[j];
        let intersect = ((pi.y > p.y) != (pj.y > p.y))
            && (p.x < (pj.x - pi.x) * (p.y - pi.y) / (pj.y - pi.y) + pi.x);
        if intersect {
            inside = !inside;
        }
        j = i;
    }
    inside
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unit_square_polygon() {
        let poly = Polygon::new(
            vec![
                Point2::new(0.0, 0.0),
                Point2::new(1.0, 0.0),
                Point2::new(1.0, 1.0),
                Point2::new(0.0, 1.0),
            ],
            vec![],
        )
        .unwrap();
        assert_eq!(poly.vertex_count_via(), 4);
        assert_eq!(poly.edges().len(), 4);
        assert_eq!(poly.hole_count(), 0);
    }

    impl Polygon {
        fn vertex_count_via(&self) -> usize {
            self.vertices().len()
        }
    }

    #[test]
    fn closing_duplicate_stripped() {
        let poly = Polygon::from_flat(
            &[[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0], [0.0, 0.0]],
            &[0],
        )
        .unwrap();
        assert_eq!(poly.vertices().len(), 4);
    }

    #[test]
    fn rejects_zero_weight() {
        let err = Pslg::from_flat(&[[0.0, 0.0], [1.0, 0.0]], &[[0, 1]], Some(&[0.0])).unwrap_err();
        assert!(matches!(err, InputError::NonPositiveWeight { .. }));
    }

    #[test]
    fn rejects_crossing() {
        let err = Pslg::from_flat(
            &[[0.0, 0.0], [1.0, 1.0], [0.0, 1.0], [1.0, 0.0]],
            &[[0, 1], [2, 3]],
            None,
        )
        .unwrap_err();
        assert!(matches!(err, InputError::CrossingConstraints { .. }));
    }

    #[test]
    fn hole_inside_square() {
        let poly = Polygon::new(
            vec![
                Point2::new(0.0, 0.0),
                Point2::new(3.0, 0.0),
                Point2::new(3.0, 3.0),
                Point2::new(0.0, 3.0),
            ],
            vec![vec![
                Point2::new(1.0, 1.0),
                Point2::new(2.0, 1.0),
                Point2::new(2.0, 2.0),
                Point2::new(1.0, 2.0),
            ]],
        )
        .unwrap();
        assert_eq!(poly.hole_count(), 1);
        assert_eq!(poly.edges().len(), 8);
    }
}