xodr 0.8.0

Pure-Rust OpenDRIVE (.xodr) importer: bakes a road network into polylines, a lane graph, and a surface mesh.
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! The area of a junction: the boundary around it, and the elevation grid
//! over it. Also junction groups, cross paths and virtual junctions.

use std::collections::HashMap;

use crate::coords::{Point, Vector};
use crate::mesh::Mesh;
use crate::network::LaneId;
use crate::road::RoadId;
use crate::structure::Coverage;
use crate::{Orientation, RoadEnd};

/// A virtual junction, from a `<junction type="virtual">`: roads that leave
/// or join a main road part way along it, such as a driveway, without
/// cutting it.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct VirtualJunction {
    /// Its `id`.
    pub od_id: String,
    /// Its `name`, empty if it has none.
    pub name: String,
    /// The road the others branch off and the stretch of it the junction
    /// spans, or `None` if the file doesn't give them, as the spec's own
    /// example of virtual connections does not.
    pub main: Option<MainRoad>,
    /// Which way along the main road it applies to, from `orientation`.
    pub orientation: Orientation,
    /// Each place in it where a road meets another part way along, in file
    /// order.
    pub links: Vec<VirtualLink>,
}

/// The road a [`VirtualJunction`]'s roads branch off, and the stretch of it
/// the junction spans.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MainRoad {
    /// The road, from `mainRoad`.
    pub road: RoadId,
    /// Where along it the junction starts, from `sStart`.
    pub s_start: f64,
    /// Where it ends, from `sEnd`.
    pub s_end: f64,
}

/// Where a road meets another part way along it, in a [`VirtualJunction`].
/// It runs the way the file links them: from a road's `<predecessor>` into
/// the road, or from the road into its `<successor>`.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct VirtualLink {
    /// Where it comes from.
    pub from: LinkPoint,
    /// Where it leads.
    pub to: LinkPoint,
    /// The lanes it joins, each a `from` lane and its `to` lane. Which way
    /// traffic crosses is the lanes' own direction.
    pub lanes: Vec<(LaneId, LaneId)>,
}

/// One side of a [`VirtualLink`].
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LinkPoint {
    /// An end of a road.
    End {
        /// The road.
        road: RoadId,
        /// Which end.
        end: RoadEnd,
    },
    /// Part way along a road, from a link's `elementS` and `elementDir`.
    Along {
        /// The road.
        road: RoadId,
        /// How far along its reference line.
        s: f64,
        /// Whether the link runs along the road's `+s` there, from
        /// `elementDir="+"`.
        forward: bool,
    },
}

impl LinkPoint {
    /// The road it is on.
    pub fn road(&self) -> RoadId {
        match *self {
            Self::End { road, .. } | Self::Along { road, .. } => road,
        }
    }
}

/// A crossing, from an OpenDRIVE `<junction type="crossing">`: where two or
/// more roads cross at one level, such as a road and a railway, and traffic
/// cannot change from one to the other. It has no connecting roads, only the
/// stretch of each road where traffic crosses.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Crossing {
    /// Its `<junction id>`.
    pub od_id: String,
    /// Its `name`, empty if it has none.
    pub name: String,
    /// Where each road crosses, from its `<roadSection>`s, in file order.
    pub sections: Vec<CrossingSection>,
}

/// One road's stretch through a [`Crossing`], from a `<roadSection>`.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CrossingSection {
    /// Its `id`, empty if it has none.
    pub od_id: String,
    /// The road.
    pub road: RoadId,
    /// Where the stretch starts along the road's reference line, `sStart`,
    /// in metres. Never past `s_end`.
    pub s_start: f64,
    /// Where it ends, `sEnd`, in metres.
    pub s_end: f64,
    /// The part of each of the road's lanes in the stretch.
    pub lanes: Vec<Coverage>,
}

/// Junctions that routing should see as one, such as the junctions round a
/// roundabout, from an OpenDRIVE `<junctionGroup>`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct JunctionGroup {
    /// Its `id`.
    pub od_id: String,
    /// Its `name`, empty if it has none.
    pub name: String,
    /// What the junctions together are.
    pub kind: JunctionGroupKind,
    /// The `<junction id>` of each junction in it, in file order.
    pub junctions: Vec<String>,
}

/// What a [`JunctionGroup`]'s junctions together are, from its `type`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum JunctionGroupKind {
    /// A roundabout.
    Roundabout,
    /// A junction built of several, such as one with slip lanes.
    ComplexJunction,
    /// Where two motorways meet.
    HighwayInterchange,
    /// The file says `unknown`, or names a type the crate doesn't know.
    Unknown,
}

/// A path across a junction's roads for pedestrians, from an OpenDRIVE
/// `<crossPath>`: a crossing road, and the lanes it joins at each end, part
/// way along them.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CrossPath {
    /// The road the path runs along.
    pub crossing: RoadId,
    /// Where it joins the lane its crossing road starts from.
    pub start: CrossPathEnd,
    /// Where it joins the lane its crossing road ends at.
    pub end: CrossPathEnd,
}

/// One end of a [`CrossPath`]: the lane of another road it joins, where
/// along that road, and the lane of the crossing road there.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CrossPathEnd {
    /// The lane of the road at this end.
    pub lane: LaneId,
    /// How far along that road's reference line the path joins it.
    pub s: f64,
    /// The crossing road's lane at this end.
    pub crossing_lane: LaneId,
}

/// A junction's area, from an OpenDRIVE junction's `<boundary>` and
/// `<elevationGrid>`: the edge of the ground its traffic may use, sidewalks
/// included, and the height of that ground.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct JunctionArea {
    /// The `<junction id>` it came from.
    pub od_id: String,
    /// The boundary, a closed ring running counter-clockwise, on the road
    /// surface. The last point is not the first again. Empty for a junction
    /// with a grid and no boundary.
    pub boundary: Vec<Point>,
    /// The height of the ground over the junction, if the junction gives
    /// one.
    pub grid: Option<ElevationGrid>,
}

/// A junction's `<elevationGrid>`: heights at evenly spaced points along the
/// junction's reference line and square to it, and the surface through them.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ElevationGrid {
    /// Where the junction's reference line starts, and its heading. It is one
    /// straight line.
    pub origin: [f64; 2],
    /// The reference line's heading, in radians.
    pub heading: f64,
    /// The `s` along the reference line of the first row of points.
    pub s_start: f64,
    /// How far apart the points are, along and across the line, in metres.
    pub spacing: f64,
    /// The rows of points, one per `<elevation>`, in order along the line.
    pub rows: Vec<GridRow>,
}

/// One row of an [`ElevationGrid`]: the heights at its points, square to the
/// junction's reference line.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GridRow {
    /// On the reference line.
    pub center: f64,
    /// To its left, from the line outward.
    pub left: Vec<f64>,
    /// To its right, from the line outward.
    pub right: Vec<f64>,
}

impl GridRow {
    /// The height `j` points to the left of the line, or to the right for a
    /// negative `j`, if the row has one there.
    fn at(&self, j: i64) -> Option<f64> {
        match j {
            0 => Some(self.center),
            j if j > 0 => self.left.get(j as usize - 1).copied(),
            j => self.right.get((-j) as usize - 1).copied(),
        }
    }
}

impl ElevationGrid {
    /// The height at `(s, t)` on the junction's reference line, or `None`
    /// outside the squares the grid covers whole, or for a coordinate that
    /// is not finite.
    ///
    /// Inside a square the height is bicubic, as the spec gives it: the
    /// square's corners, and their slopes along and across the line and
    /// their twist, each from the cubic through the four points of the row
    /// or column the square's edge lies on. Where the grid has too few points
    /// for that cubic, the slope is the straight line along the edge.
    pub fn height(&self, s: f64, t: f64) -> Option<f64> {
        if self.spacing.is_nan() || self.spacing <= 0.0 {
            return None;
        }
        let snap = |at: f64| {
            if (at - at.round()).abs() < 1e-6 {
                at.round()
            } else {
                at
            }
        };
        let (u, v) = (
            snap((s - self.s_start) / self.spacing),
            snap(t / self.spacing),
        );
        let last_row = self.rows.len().checked_sub(1)? as f64;
        let widest = self
            .rows
            .iter()
            .map(|row| row.left.len().max(row.right.len()))
            .max()? as f64;
        if !(0.0..=last_row).contains(&u) || !(-widest..=widest).contains(&v) {
            return None;
        }
        // A point on a grid line is on the edge of the squares either side.
        let squares = |at: f64| {
            let i = at.floor() as i64;
            let frac = at - i as f64;
            if frac == 0.0 {
                vec![(i, 0.0), (i - 1, 1.0)]
            } else {
                vec![(i, frac)]
            }
        };
        let (rows, columns) = (squares(u), squares(v));
        rows.iter()
            .flat_map(|&row| columns.iter().map(move |&column| (row, column)))
            .find_map(|((i, x), (j, y))| self.in_square(i, x, j, y))
    }

    /// The bicubic height at `(x, y)` within the square from grid point
    /// `(i, j)`, or `None` if the grid lacks a point it needs.
    fn in_square(&self, i: i64, x: f64, j: i64, y: f64) -> Option<f64> {
        let z = |i: i64, j: i64| self.value(i, j);
        let dt = |i: i64| slopes(|k| z(i, j - 1 + k));
        let [z00, z01, z10, z11] = [z(i, j)?, z(i, j + 1)?, z(i + 1, j)?, z(i + 1, j + 1)?];
        let (t0, t1) = (dt(i)?, dt(i + 1)?);
        let (s0, s1) = (
            slopes(|k| z(i - 1 + k, j))?,
            slopes(|k| z(i - 1 + k, j + 1))?,
        );
        let (st0, st1) = (
            slopes(|k| dt(i - 1 + k).map(|d| d.0))?,
            slopes(|k| dt(i - 1 + k).map(|d| d.1))?,
        );
        let f = [
            [z00, z01, t0.0, t0.1],
            [z10, z11, t1.0, t1.1],
            [s0.0, s1.0, st0.0, st1.0],
            [s0.1, s1.1, st0.1, st1.1],
        ];
        let alpha = mul(&mul(&A, &f), &transpose(&A));
        let powers = |x: f64| [1.0, x, x * x, x * x * x];
        let (px, py) = (powers(x), powers(y));
        Some(
            (0..4)
                .flat_map(|r| (0..4).map(move |c| (r, c)))
                .map(|(r, c)| px[r] * alpha[r][c] * py[c])
                .sum(),
        )
    }

    /// The height at grid point `(i, j)`: row `i`, `j` points to the left
    /// of the line.
    fn value(&self, i: i64, j: i64) -> Option<f64> {
        usize::try_from(i)
            .ok()
            .and_then(|i| self.rows.get(i))
            .and_then(|row| row.at(j))
    }

    /// The height under `(x, y)`, or `None` where the grid does not reach.
    pub(crate) fn height_at(&self, x: f64, y: f64) -> Option<f64> {
        let (s, t) = self.locate(x, y);
        self.height(s, t)
    }

    /// Where `(x, y)` is on the junction's reference line: `s` along it and
    /// `t` to its left.
    fn locate(&self, x: f64, y: f64) -> (f64, f64) {
        let (sin, cos) = self.heading.sin_cos();
        let (dx, dy) = (x - self.origin[0], y - self.origin[1]);
        (dx * cos + dy * sin, dy * cos - dx * sin)
    }
}

/// The matrix the spec's bicubic interpolation turns a square's corners and
/// slopes into its coefficients with.
const A: [[f64; 4]; 4] = [
    [1.0, 0.0, 0.0, 0.0],
    [0.0, 0.0, 1.0, 0.0],
    [-3.0, 3.0, -2.0, -1.0],
    [2.0, -2.0, 1.0, 1.0],
];

fn mul(a: &[[f64; 4]; 4], b: &[[f64; 4]; 4]) -> [[f64; 4]; 4] {
    let mut out = [[0.0; 4]; 4];
    for (r, row) in out.iter_mut().enumerate() {
        for (c, cell) in row.iter_mut().enumerate() {
            *cell = (0..4).map(|k| a[r][k] * b[k][c]).sum();
        }
    }
    out
}

fn transpose(a: &[[f64; 4]; 4]) -> [[f64; 4]; 4] {
    let mut out = [[0.0; 4]; 4];
    for (r, row) in a.iter().enumerate() {
        for (c, &cell) in row.iter().enumerate() {
            out[c][r] = cell;
        }
    }
    out
}

/// The slopes at points 1 and 2 of four evenly spaced points 0 to 3, a grid
/// step apart, from the cubic through all four. From the line through 1 and
/// 2 where 0 or 3 is missing, and `None` where 1 or 2 is.
fn slopes(value: impl Fn(i64) -> Option<f64>) -> Option<(f64, f64)> {
    let (b, c) = (value(1)?, value(2)?);
    match (value(0), value(3)) {
        (Some(a), Some(d)) => Some((
            (-2.0 * a - 3.0 * b + 6.0 * c - d) / 6.0,
            (a - 6.0 * b + 3.0 * c + 2.0 * d) / 6.0,
        )),
        _ => Some((c - b, c - b)),
    }
}

impl JunctionArea {
    /// The ground's height under `(x, y)`, from the elevation grid, or
    /// `None` where the junction has no grid or the grid does not reach.
    pub fn height_at(&self, x: f64, y: f64) -> Option<f64> {
        self.grid.as_ref()?.height_at(x, y)
    }

    /// The ground inside the boundary as triangles, split to the grid's
    /// spacing and stood at the grid's height where it reaches, or at the
    /// boundary's height across each triangle where it doesn't. Empty for an
    /// area without a boundary.
    ///
    /// Each triangle of the boundary splits evenly by its longest edge. Two
    /// that share an edge may split it differently, so each puts a vertex
    /// on it wherever either does, and the ground has no cracks.
    pub fn mesh(&self) -> Mesh {
        let ring = &self.boundary;
        let step = self.grid.as_ref().map_or(f64::INFINITY, |g| g.spacing);
        let triangles = ear_clip(ring);
        let counts: Vec<usize> = triangles
            .iter()
            .map(|&[a, b, c]| {
                let longest = [(a, b), (b, c), (c, a)]
                    .map(|(p, q)| ring[p].distance_to(ring[q]))
                    .into_iter()
                    .fold(0.0_f32, f32::max);
                (f64::from(longest) / step).ceil().clamp(1.0, 64.0) as usize
            })
            .collect();
        let mut splits: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
        for (&[a, b, c], &n) in triangles.iter().zip(&counts) {
            for (p, q) in [(a, b), (b, c), (c, a)] {
                splits.entry((p.min(q), p.max(q))).or_default().push(n);
            }
        }
        let stand = |p: Point| {
            let z = self.height_at(f64::from(p.x), f64::from(p.y));
            Point::new(p.x, p.y, z.map_or(p.z, |z| z as f32))
        };
        let on_edge = |a: usize, b: usize, num: usize, den: usize| {
            let (from, to, num) = if a < b {
                (a, b, num)
            } else {
                (b, a, den - num)
            };
            match num {
                0 => stand(ring[from]),
                _ if num == den => stand(ring[to]),
                _ => stand(ring[from].lerp(ring[to], num as f32 / den as f32)),
            }
        };
        let between = |a: usize, b: usize, lo: usize, n: usize| {
            let mut found: Vec<(usize, usize)> = Vec::new();
            for &m in &splits[&(a.min(b), a.max(b))] {
                found.extend(
                    (lo * m / n + 1..)
                        .take_while(|k| k * n < (lo + 1) * m)
                        .map(|k| (k, m)),
                );
            }
            found.sort_by(|x, y| (x.0 * y.1).cmp(&(y.0 * x.1)));
            found.dedup_by(|x, y| x.0 * y.1 == y.0 * x.1);
            found.into_iter().map(move |(k, m)| on_edge(a, b, k, m))
        };
        let mut mesh = Mesh::default();
        for (&[a, b, c], &n) in triangles.iter().zip(&counts) {
            let (pa, pb, pc) = (ring[a], ring[b], ring[c]);
            let vertex = |i: usize, j: usize| match (i, j) {
                (_, 0) => on_edge(a, b, i, n),
                (0, _) => on_edge(c, a, n - j, n),
                _ if i + j == n => on_edge(b, c, j, n),
                _ => {
                    let (u, v) = (i as f32 / n as f32, j as f32 / n as f32);
                    stand(pa + (pb - pa) * u + (pc - pa) * v)
                }
            };
            for i in 0..n {
                for j in 0..n - i {
                    let mut ring_of = vec![vertex(i, j)];
                    if j == 0 {
                        ring_of.extend(between(a, b, i, n));
                    }
                    ring_of.push(vertex(i + 1, j));
                    if i + j + 1 == n {
                        ring_of.extend(between(b, c, j, n));
                    }
                    ring_of.push(vertex(i, j + 1));
                    if i == 0 {
                        ring_of.extend(between(c, a, n - j - 1, n));
                    }
                    fan(&mut mesh, &ring_of);
                    if i + j + 1 < n {
                        push(
                            &mut mesh,
                            [vertex(i + 1, j), vertex(i + 1, j + 1), vertex(i, j + 1)],
                        );
                    }
                }
            }
        }
        mesh
    }
}

/// The convex polygon `corners`, counter-clockwise, as triangles: itself if
/// it has three corners, else a fan round its centroid.
fn fan(mesh: &mut Mesh, corners: &[Point]) {
    if let [a, b, c] = corners {
        return push(mesh, [*a, *b, *c]);
    }
    let sum = corners
        .iter()
        .fold(Vector::ZERO, |s, p| s + (*p - Point::ORIGIN));
    let centre = Point::ORIGIN + sum * (1.0 / corners.len() as f32);
    for (k, p) in corners.iter().enumerate() {
        push(mesh, [*p, corners[(k + 1) % corners.len()], centre]);
    }
}

/// Add one triangle to `mesh`, with its own vertices and its face's normal,
/// turned up.
fn push(mesh: &mut Mesh, corners: [Point; 3]) {
    let normal = (corners[1] - corners[0])
        .cross(corners[2] - corners[0])
        .normalize_or(Vector::Z);
    let normal = if normal.z < 0.0 {
        normal * -1.0
    } else {
        normal
    };
    let first = mesh.vertices.len() as u32;
    mesh.vertices.extend(corners);
    mesh.normals.extend([normal; 3]);
    mesh.indices.extend([first, first + 1, first + 2]);
}

/// How close, in metres, two points of a boundary may be before
/// [`ear_clip`] takes them as one: the lanes it runs along can overlap by
/// millimetres where roads meet, folding the ring back on itself.
const NEAR: f32 = 0.01;

/// The triangles of a simple counter-clockwise polygon in plan, as indices
/// into `ring`, by clipping its ears. A corner where the ring runs straight
/// on is clipped without a triangle. Only a corner that turns right can lie
/// in an ear, so only those are tested. A ring that crosses itself can leave
/// a part with no ear, which stays untriangulated.
fn ear_clip(ring: &[Point]) -> Vec<[usize; 3]> {
    let cross =
        |o: Point, a: Point, b: Point| (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
    let inside = |p: Point, [a, b, c]: [Point; 3]| {
        cross(a, b, p) > 0.0 && cross(b, c, p) > 0.0 && cross(c, a, p) > 0.0
    };
    let n = ring.len();
    let straight = |k: usize| {
        let (a, b, c) = (ring[(k + n - 1) % n], ring[k], ring[(k + 1) % n]);
        let scale = (c.x - a.x).hypot(c.y - a.y).powi(2);
        cross(a, b, c).abs() <= 1e-6 * scale
    };
    let mut left: Vec<usize> = Vec::new();
    for k in (0..n).filter(|&k| !straight(k)) {
        let near = |j: &usize| ring[*j].distance_to(ring[k]) < NEAR;
        if !left.last().is_some_and(near) && !(k + 1 == n && left.first().is_some_and(near)) {
            left.push(k);
        }
    }
    let mut out = Vec::new();
    while left.len() > 3 {
        let n = left.len();
        let corner = |k: usize| (left[(k + n - 1) % n], left[k % n], left[(k + 1) % n]);
        let turn = |k: usize| {
            let (a, b, c) = corner(k);
            cross(ring[a], ring[b], ring[c])
        };
        let reflex: Vec<usize> = (0..n).filter(|&k| turn(k) < 0.0).map(|k| left[k]).collect();
        let ear = (0..n).find(|&k| {
            let (a, b, c) = corner(k);
            let corners = [ring[a], ring[b], ring[c]];
            turn(k) > 0.0
                && !reflex
                    .iter()
                    .any(|&p| p != a && p != c && inside(ring[p], corners))
        });
        if let Some(k) = ear {
            let (a, b, c) = corner(k);
            out.push([a, b, c]);
            left.remove(k);
        } else if let Some(k) = (0..n).find(|&k| turn(k) == 0.0) {
            left.remove(k);
        } else {
            break;
        }
    }
    if left.len() == 3 && cross(ring[left[0]], ring[left[1]], ring[left[2]]) > 0.0 {
        out.push([left[0], left[1], left[2]]);
    }
    out
}

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

    fn grid(rows: Vec<GridRow>) -> ElevationGrid {
        ElevationGrid {
            origin: [0.0, 0.0],
            heading: 0.0,
            s_start: 0.0,
            spacing: 2.0,
            rows,
        }
    }

    fn row(center: f64, left: &[f64], right: &[f64]) -> GridRow {
        GridRow {
            center,
            left: left.to_vec(),
            right: right.to_vec(),
        }
    }

    #[test]
    fn a_flat_grid_is_flat_and_ends_at_its_last_whole_square() {
        let g = grid(vec![row(5.0, &[5.0], &[5.0]); 3]);
        for (s, t) in [(0.0, 0.0), (1.3, -1.7), (3.9, 1.9), (4.0, 2.0)] {
            assert!((g.height(s, t).unwrap() - 5.0).abs() < 1e-12, "({s}, {t})");
        }
        assert!(g.height(4.1, 0.0).is_none());
        assert!(g.height(1.0, 2.1).is_none());
        assert!(g.height(-0.1, 0.0).is_none());
    }

    #[test]
    fn a_coordinate_far_off_or_not_finite_has_no_height() {
        let g = grid(vec![row(5.0, &[5.0], &[5.0]); 3]);
        for (s, t) in [
            (f64::NAN, 0.0),
            (0.0, f64::NAN),
            (f64::INFINITY, 0.0),
            (0.0, f64::NEG_INFINITY),
            (1e30, 0.0),
            (2.0, -1e30),
        ] {
            assert!(g.height(s, t).is_none(), "({s}, {t})");
        }
        let fine = ElevationGrid {
            spacing: 1e-300,
            ..g.clone()
        };
        assert!(fine.height(1.0, 0.0).is_none());
        assert!(grid(Vec::new()).height(0.0, 0.0).is_none());
    }

    #[test]
    fn a_grid_passes_through_its_points_and_is_exact_on_a_plane() {
        let plane = |s: f64, t: f64| 1.0 + 0.1 * s - 0.05 * t;
        let rows = (0..5)
            .map(|i| {
                let s = 2.0 * i as f64;
                row(
                    plane(s, 0.0),
                    &[plane(s, 2.0), plane(s, 4.0)],
                    &[plane(s, -2.0), plane(s, -4.0)],
                )
            })
            .collect();
        let g = grid(rows);
        for (s, t) in [(2.0, 2.0), (3.1, -0.7), (5.5, 3.3), (7.9, -3.9)] {
            assert!(
                (g.height(s, t).unwrap() - plane(s, t)).abs() < 1e-9,
                "({s}, {t})"
            );
        }
    }

    #[test]
    fn a_grid_follows_a_cubic_along_the_line_between_its_points() {
        // Heights on a cubic along s: the four-point cubic slopes make the
        // interpolation exact inside the middle square.
        let f = |s: f64| 0.01 * s * s * s - 0.2 * s + 1.0;
        let rows = (0..4).map(|i| {
            let z = f(2.0 * i as f64);
            row(z, &[z], &[z])
        });
        let g = grid(rows.collect());
        for s in [2.0, 2.5, 3.0, 3.7] {
            assert!((g.height(s, 0.5).unwrap() - f(s)).abs() < 1e-9, "{s}");
        }
    }

    #[test]
    fn a_square_ring_clips_to_two_triangles_and_meshes_at_the_grid_spacing() {
        let ring = vec![
            Point::new(0.0, 0.0, 0.0),
            Point::new(4.0, 0.0, 0.0),
            Point::new(4.0, 4.0, 0.0),
            Point::new(0.0, 4.0, 0.0),
        ];
        assert_eq!(ear_clip(&ring).len(), 2);
        let mut area = JunctionArea {
            od_id: "1".into(),
            boundary: ring.clone(),
            grid: None,
        };
        assert_eq!(area.mesh().indices.len(), 6);
        area.grid = Some(ElevationGrid {
            origin: [0.0, 0.0],
            heading: 0.0,
            s_start: 0.0,
            spacing: 2.0,
            rows: vec![row(3.0, &[3.0, 3.0], &[]); 3],
        });
        let mesh = area.mesh();
        mesh.validate().unwrap();
        assert!(mesh.indices.len() > 6);
        assert!(mesh.vertices.iter().all(|v| (v.z - 3.0).abs() < 1e-6));
        assert!(mesh.normals.iter().all(|n| n.z > 0.99));
    }

    #[test]
    fn a_concave_ring_clips_without_covering_its_notch() {
        let ring = vec![
            Point::new(0.0, 0.0, 0.0),
            Point::new(4.0, 0.0, 0.0),
            Point::new(4.0, 4.0, 0.0),
            Point::new(2.0, 1.0, 0.0),
            Point::new(0.0, 4.0, 0.0),
        ];
        let triangles = ear_clip(&ring);
        assert_eq!(triangles.len(), 3);
        let area: f32 = triangles
            .iter()
            .map(|&[a, b, c]| {
                let (a, b, c) = (ring[a], ring[b], ring[c]);
                ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) / 2.0
            })
            .sum();
        assert!((area - 10.0).abs() < 1e-5, "{area}");
    }
}