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
//! Intermediate structures used to instantiate a Scenario. Badly needs simplification:
//! https://github.com/a-b-street/abstreet/issues/258

use anyhow::Result;
use serde::{Deserialize, Serialize};

use map_model::{BuildingID, Map, PathConstraints, Position, TransitRouteID, TransitStopID};
use synthpop::{TripEndpoint, TripMode};

use crate::{CarID, DrivingGoal, SidewalkSpot, TripLeg, VehicleType, SPAWN_DIST};

/// We need to remember a few things from scenario instantiation that're used for starting the
/// trip.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub(crate) struct StartTripArgs {
    pub retry_if_no_room: bool,
    pub use_vehicle: Option<CarID>,
}

// TODO Some of these fields are unused now that we separately pass TripEndpoint
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub(crate) enum TripSpec {
    /// Can be used to spawn from a border or anywhere for interactive debugging.
    VehicleAppearing {
        start_pos: Position,
        goal: DrivingGoal,
        /// This must be a currently off-map vehicle owned by the person.
        use_vehicle: CarID,
        retry_if_no_room: bool,
    },
    /// Something went wrong spawning the trip.
    SpawningFailure {
        use_vehicle: Option<CarID>,
        error: String,
    },
    UsingParkedCar {
        /// This must be a currently parked vehicle owned by the person.
        car: CarID,
        start_bldg: BuildingID,
        goal: DrivingGoal,
    },
    JustWalking {
        start: SidewalkSpot,
        goal: SidewalkSpot,
    },
    UsingBike {
        bike: CarID,
        start: BuildingID,
        goal: DrivingGoal,
    },
    UsingTransit {
        start: SidewalkSpot,
        goal: SidewalkSpot,
        route: TransitRouteID,
        stop1: TransitStopID,
        maybe_stop2: Option<TransitStopID>,
    },
}

impl TripSpec {
    pub fn into_plan(self, map: &Map) -> (TripSpec, Vec<TripLeg>) {
        // TODO We'll want to repeat this validation when we spawn stuff later for a second leg...
        let mut legs = Vec::new();
        match &self {
            TripSpec::VehicleAppearing {
                start_pos,
                goal,
                use_vehicle,
                ..
            } => {
                if start_pos.dist_along() >= map.get_l(start_pos.lane()).length() {
                    panic!("Can't spawn at {}; it isn't that long", start_pos);
                }
                if let DrivingGoal::Border(_, end_lane) = goal {
                    if start_pos.lane() == *end_lane
                        && start_pos.dist_along() == map.get_l(*end_lane).length()
                    {
                        panic!(
                            "Can't start at {}; it's the edge of a border already",
                            start_pos
                        );
                    }
                }

                let constraints = if use_vehicle.vehicle_type == VehicleType::Bike {
                    PathConstraints::Bike
                } else {
                    PathConstraints::Car
                };

                legs.push(TripLeg::Drive(*use_vehicle, goal.clone()));
                if let DrivingGoal::ParkNear(b) = goal {
                    legs.push(TripLeg::Walk(SidewalkSpot::building(*b, map)));
                }

                if goal.goal_pos(constraints, map).is_none() {
                    return TripSpec::SpawningFailure {
                        use_vehicle: Some(*use_vehicle),
                        error: format!("goal_pos to {:?} for a {:?} failed", goal, constraints),
                    }
                    .into_plan(map);
                }
            }
            TripSpec::SpawningFailure { .. } => {
                // TODO The legs are a lie. Since the trip gets cancelled, this doesn't matter.
                // I'm not going to bother doing better because I think TripLeg will get
                // revamped soon anyway.
                legs.push(TripLeg::RideBus(TransitRouteID(0), None));
            }
            TripSpec::UsingParkedCar { car, goal, .. } => {
                legs.push(TripLeg::Walk(SidewalkSpot::deferred_parking_spot()));
                legs.push(TripLeg::Drive(*car, goal.clone()));
                match goal {
                    DrivingGoal::ParkNear(b) => {
                        legs.push(TripLeg::Walk(SidewalkSpot::building(*b, map)));
                    }
                    DrivingGoal::Border(_, _) => {}
                }
            }
            TripSpec::JustWalking { start, goal, .. } => {
                if start == goal {
                    panic!(
                        "A trip just walking from {:?} to {:?} doesn't make sense",
                        start, goal
                    );
                }
                legs.push(TripLeg::Walk(goal.clone()));
            }
            TripSpec::UsingBike { start, goal, bike } => {
                // TODO Might not be possible to walk to the same border if there's no sidewalk
                let backup_plan = match goal {
                    DrivingGoal::ParkNear(b) => Some(TripSpec::JustWalking {
                        start: SidewalkSpot::building(*start, map),
                        goal: SidewalkSpot::building(*b, map),
                    }),
                    DrivingGoal::Border(i, _) => {
                        SidewalkSpot::end_at_border(*i, map).map(|goal| TripSpec::JustWalking {
                            start: SidewalkSpot::building(*start, map),
                            goal,
                        })
                    }
                };

                if let Some(start_spot) = SidewalkSpot::bike_rack(*start, map) {
                    if let DrivingGoal::ParkNear(b) = goal {
                        if let Some(goal_spot) = SidewalkSpot::bike_rack(*b, map) {
                            if start_spot.sidewalk_pos.lane() == goal_spot.sidewalk_pos.lane() {
                                info!(
                                    "Bike trip from {} to {} will just walk; it's the same \
                                     sidewalk!",
                                    start, b
                                );
                                return backup_plan.unwrap().into_plan(map);
                            }
                        } else {
                            info!(
                                "Can't find biking connection for goal {}, walking instead",
                                b
                            );
                            return backup_plan.unwrap().into_plan(map);
                        }
                    }

                    legs.push(TripLeg::Walk(start_spot));
                    legs.push(TripLeg::Drive(*bike, goal.clone()));
                    match goal {
                        DrivingGoal::ParkNear(b) => {
                            legs.push(TripLeg::Walk(SidewalkSpot::building(*b, map)));
                        }
                        DrivingGoal::Border(_, _) => {}
                    }
                } else if let Some(plan) = backup_plan {
                    info!("Can't start biking from {}. Walking instead", start);
                    return plan.into_plan(map);
                } else {
                    return TripSpec::SpawningFailure {
                        use_vehicle: Some(*bike),
                        error: format!(
                            "Can't start biking from {} and can't walk either! Goal is {:?}",
                            start, goal
                        ),
                    }
                    .into_plan(map);
                }
            }
            TripSpec::UsingTransit {
                route,
                stop1,
                maybe_stop2,
                goal,
                ..
            } => {
                let walk_to = SidewalkSpot::bus_stop(*stop1, map);
                if let Some(stop2) = maybe_stop2 {
                    legs = vec![
                        TripLeg::Walk(walk_to),
                        TripLeg::RideBus(*route, Some(*stop2)),
                        TripLeg::Walk(goal.clone()),
                    ];
                } else {
                    legs = vec![TripLeg::Walk(walk_to), TripLeg::RideBus(*route, None)];
                }
            }
        };

        (self, legs)
    }

    /// Turn an origin/destination pair and mode into a specific plan for instantiating a trip.
    /// Decisions like how to use public transit happen here.
    pub fn maybe_new(
        from: TripEndpoint,
        to: TripEndpoint,
        mode: TripMode,
        use_vehicle: Option<CarID>,
        retry_if_no_room: bool,
        map: &Map,
    ) -> Result<TripSpec> {
        Ok(match mode {
            TripMode::Drive | TripMode::Bike => {
                let constraints = if mode == TripMode::Drive {
                    PathConstraints::Car
                } else {
                    PathConstraints::Bike
                };
                let goal = driving_goal(to, constraints, map)?;
                match from {
                    TripEndpoint::Building(start_bldg) => {
                        if mode == TripMode::Drive {
                            TripSpec::UsingParkedCar {
                                start_bldg,
                                goal,
                                car: use_vehicle.unwrap(),
                            }
                        } else {
                            TripSpec::UsingBike {
                                start: start_bldg,
                                goal,
                                bike: use_vehicle.unwrap(),
                            }
                        }
                    }
                    TripEndpoint::Border(i) => {
                        let start_lane = map
                            .get_i(i)
                            .some_outgoing_road(map)
                            // TODO Since we're now doing this right when the trip is starting,
                            // pick the least loaded lane or similar.
                            .and_then(|dr| dr.lanes(constraints, map).pop())
                            .ok_or_else(|| {
                                anyhow!("can't start a {} trip from {}", mode.ongoing_verb(), i)
                            })?;
                        TripSpec::VehicleAppearing {
                            start_pos: Position::new(start_lane, SPAWN_DIST),
                            goal,
                            use_vehicle: use_vehicle.unwrap(),
                            retry_if_no_room,
                        }
                    }
                    TripEndpoint::SuddenlyAppear(start_pos) => TripSpec::VehicleAppearing {
                        start_pos,
                        goal,
                        use_vehicle: use_vehicle.unwrap(),
                        retry_if_no_room,
                    },
                }
            }
            TripMode::Walk => TripSpec::JustWalking {
                start: start_sidewalk_spot(from, map)?,
                goal: end_sidewalk_spot(to, map)?,
            },
            TripMode::Transit => {
                let start = start_sidewalk_spot(from, map)?;
                let goal = end_sidewalk_spot(to, map)?;
                if let Some((stop1, maybe_stop2, route)) =
                    map.should_use_transit(start.sidewalk_pos, goal.sidewalk_pos)
                {
                    TripSpec::UsingTransit {
                        start,
                        goal,
                        route,
                        stop1,
                        maybe_stop2,
                    }
                } else {
                    //warn!("{:?} not actually using transit, because pathfinding didn't find any
                    // useful route", trip);
                    TripSpec::JustWalking { start, goal }
                }
            }
        })
    }
}

fn start_sidewalk_spot(endpt: TripEndpoint, map: &Map) -> Result<SidewalkSpot> {
    match endpt {
        TripEndpoint::Building(b) => Ok(SidewalkSpot::building(b, map)),
        TripEndpoint::Border(i) => SidewalkSpot::start_at_border(i, map)
            .ok_or_else(|| anyhow!("can't start walking from {}", i)),
        TripEndpoint::SuddenlyAppear(pos) => Ok(SidewalkSpot::suddenly_appear(pos, map)),
    }
}

fn end_sidewalk_spot(endpt: TripEndpoint, map: &Map) -> Result<SidewalkSpot> {
    match endpt {
        TripEndpoint::Building(b) => Ok(SidewalkSpot::building(b, map)),
        TripEndpoint::Border(i) => {
            SidewalkSpot::end_at_border(i, map).ok_or_else(|| anyhow!("can't end walking at {}", i))
        }
        TripEndpoint::SuddenlyAppear(_) => unreachable!(),
    }
}

fn driving_goal(
    endpt: TripEndpoint,
    constraints: PathConstraints,
    map: &Map,
) -> Result<DrivingGoal> {
    match endpt {
        TripEndpoint::Building(b) => Ok(DrivingGoal::ParkNear(b)),
        // TODO Duplicates some logic from TripEndpoint::pos
        TripEndpoint::Border(i) => map
            .get_i(i)
            .some_incoming_road(map)
            .and_then(|dr| {
                let lanes = dr.lanes(constraints, map);
                if lanes.is_empty() {
                    None
                } else {
                    // TODO ideally could use any
                    Some(DrivingGoal::Border(dr.dst_i(map), lanes[0]))
                }
            })
            .ok_or_else(|| anyhow!("can't end at {} for {:?}", i, constraints)),
        TripEndpoint::SuddenlyAppear(_) => unreachable!(),
    }
}