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
use abstutil::Tags;

use crate::{Direction, DrivingSide, LaneSpec, LaneType};

impl LaneSpec {
    /// Returns the index where the new lane was inserted
    pub fn add_new_lane(
        lanes_ltr: &mut Vec<LaneSpec>,
        lt: LaneType,
        osm_tags: &Tags,
        driving_side: DrivingSide,
    ) -> usize {
        let mut dir = Direction::Fwd;
        let mut idx = 0;

        match lt {
            LaneType::Driving => {
                dir = determine_lane_dir(lanes_ltr, lt, true);
                // In the middle (where the direction changes)
                idx = lanes_ltr
                    .windows(2)
                    .position(|pair| pair[0].dir != pair[1].dir)
                    .map(|x| x + 1)
                    .unwrap_or(lanes_ltr.len());
            }
            LaneType::Biking | LaneType::Bus | LaneType::Parking | LaneType::Construction => {
                let relevant_lanes: Vec<&LaneSpec> =
                    lanes_ltr.iter().filter(|x| x.lt == lt).collect();
                dir = if !relevant_lanes.is_empty() {
                    // When a lane already exists, then default to the direction on the other side of
                    // the road
                    relevant_lanes[0].dir.opposite()
                } else {
                    // If no lanes exist, then default to the majority direction, to help deal with
                    // one-way streets
                    determine_lane_dir(lanes_ltr, lt, false)
                };

                // Place on the dir side, before any sidewalk
                idx = default_outside_lane_placement(lanes_ltr, dir);
            }
            LaneType::Sidewalk => {
                // Place where it's missing
                if !lanes_ltr[0].lt.is_walkable() {
                    idx = 0;
                    dir = if driving_side == DrivingSide::Right {
                        Direction::Back
                    } else {
                        Direction::Fwd
                    };
                } else {
                    idx = lanes_ltr.len();
                    dir = if driving_side == DrivingSide::Right {
                        Direction::Fwd
                    } else {
                        Direction::Back
                    };
                }
            }
            LaneType::Buffer(_) => {
                // Look for the bike lane that's missing a buffer
                let mut fwd_bike = None;
                let mut back_bike = None;
                for (idx, spec) in lanes_ltr.iter().enumerate() {
                    if spec.lt == LaneType::Biking {
                        if spec.dir == Direction::Fwd {
                            fwd_bike = Some(idx);
                        } else {
                            back_bike = Some(idx);
                        }
                    }
                }
                // TODO This is US-centric, since it assumes the Fwd direction is on the right. We
                // should probably decompose into sides like maybe_add_bike_lanes.
                if let Some(i) = fwd_bike {
                    // If there's nothing to the left of this bike lane, not sure what's going on...
                    if lanes_ltr
                        .get(i - 1)
                        .map(|spec| !matches!(spec.lt, LaneType::Buffer(_)))
                        .unwrap_or(false)
                    {
                        dir = Direction::Fwd;
                        idx = i;
                    }
                }
                if let Some(i) = back_bike {
                    if lanes_ltr
                        .get(i + 1)
                        .map(|spec| !matches!(spec.lt, LaneType::Buffer(_)))
                        .unwrap_or(false)
                    {
                        dir = Direction::Back;
                        idx = i + 1;
                    }
                }
            }
            _ => unreachable!(),
        };

        lanes_ltr.insert(
            idx,
            LaneSpec {
                lt,
                dir,
                width: LaneSpec::typical_lane_widths(lt, osm_tags)[0].0,
            },
        );
        idx
    }
}

/// Place the new lane according to its direction on the outside unless the outside is walkable in
/// which case place inside the walkable lane
fn default_outside_lane_placement(lanes_ltr: &[LaneSpec], dir: Direction) -> usize {
    if lanes_ltr[0].dir == dir {
        if lanes_ltr[0].lt.is_walkable() {
            1
        } else {
            0
        }
    } else if lanes_ltr.last().unwrap().lt.is_walkable() {
        lanes_ltr.len() - 1
    } else {
        lanes_ltr.len()
    }
}

/// If there are more lanes of type lt pointing forward, then insert the new one backwards, and
/// vice versa
fn determine_lane_dir(lanes_ltr: &[LaneSpec], lt: LaneType, minority: bool) -> Direction {
    if (lanes_ltr
        .iter()
        .filter(|x| x.dir == Direction::Fwd && x.lt == lt)
        .count() as f64
        / lanes_ltr.iter().filter(|x| x.lt == lt).count() as f64)
        <= 0.5
    {
        if minority {
            Direction::Fwd
        } else {
            Direction::Back
        }
    } else if minority {
        Direction::Back
    } else {
        Direction::Fwd
    }
}

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

    #[test]
    fn test_add_new_lane() {
        let mut ok = true;
        for (description, input_lt, input_dir, new_lt, expected_lt, expected_dir) in vec![
            (
                "Two-way with parking, adding bike lane to first side",
                "spddps",
                "vvv^^^",
                LaneType::Biking,
                // TODO Current heuristics put it between parking and sidewalk, but this isn't
                // right
                "spddpbs",
                "vvv^^^^",
            ),
            (
                "Two-way with parking, adding bike lane to second side",
                "spddpbs",
                "vvv^^^^",
                LaneType::Biking,
                // TODO Current heuristics put it between parking and sidewalk, but this isn't
                // right
                "sbpddpbs",
                "vvvv^^^^",
            ),
            (
                "Add driving lane, balanced numbers",
                "sdds",
                "vv^^",
                LaneType::Driving,
                "sddds",
                "vv^^^",
            ),
            (
                "Add driving lane, imbalanced",
                "sddds",
                "vv^^^",
                LaneType::Driving,
                "sdddds",
                "vvv^^^",
            ),
            (
                "Add buffer, one bike lane fwd",
                "sddbs",
                "vv^^^",
                LaneType::Buffer(BufferType::Stripes),
                "sdd|bs",
                "vv^^^^",
            ),
            (
                "Add buffer, one bike lane back",
                "sbdds",
                "vvv^^",
                LaneType::Buffer(BufferType::Stripes),
                "sb|dds",
                "vvvv^^",
            ),
            (
                "Add second buffer",
                "sbdd|bs",
                "vvv^^^^",
                LaneType::Buffer(BufferType::Stripes),
                "sb|dd|bs",
                "vvvv^^^^",
            ),
        ] {
            let input = LaneSpec::create_for_test(input_lt, input_dir);
            let mut actual_output = input.clone();
            LaneSpec::add_new_lane(
                &mut actual_output,
                new_lt,
                &Tags::empty(),
                DrivingSide::Right,
            );
            LaneSpec::check_lanes_ltr(
                &actual_output,
                description.to_string(),
                input_lt,
                input_dir,
                expected_lt,
                expected_dir,
                &mut ok,
            );
        }
        assert!(ok);
    }
}