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
use crate::{
    CarID, Command, DrivingGoal, OffMapLocation, Person, PersonID, Scheduler, SidewalkSpot,
    TripEndpoint, TripLeg, TripManager, TripMode, VehicleType,
};
use abstutil::{Parallelism, Timer};
use geom::{Duration, Time};
use map_model::{
    BuildingID, BusRouteID, BusStopID, IntersectionID, Map, PathConstraints, PathRequest, Position,
};
use serde::{Deserialize, Serialize};

// TODO Some of these fields are unused now that we separately pass TripEndpoint
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub 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,
        origin: Option<OffMapLocation>,
    },
    // A VehicleAppearing that failed to even pick a start_pos, because of a bug with badly chosen
    // borders.
    NoRoomToSpawn {
        i: IntersectionID,
        goal: DrivingGoal,
        use_vehicle: CarID,
        origin: Option<OffMapLocation>,
        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: BusRouteID,
        stop1: BusStopID,
        maybe_stop2: Option<BusStopID>,
    },
    // Completely off-map trip. Don't really simulate much of it.
    Remote {
        from: OffMapLocation,
        to: OffMapLocation,
        trip_time: Duration,
        mode: TripMode,
    },
}

// This structure is created temporarily by a Scenario or to interactively spawn agents.
pub struct TripSpawner {
    trips: Vec<(PersonID, Time, TripSpec, TripEndpoint, bool, bool)>,
}

impl TripSpawner {
    pub fn new() -> TripSpawner {
        TripSpawner { trips: Vec::new() }
    }

    pub fn schedule_trip(
        &mut self,
        person: &Person,
        start_time: Time,
        mut spec: TripSpec,
        trip_start: TripEndpoint,
        cancelled: bool,
        modified: bool,
        map: &Map,
    ) {
        // TODO We'll want to repeat this validation when we spawn stuff later for a second leg...
        match &spec {
            TripSpec::VehicleAppearing {
                start_pos,
                goal,
                use_vehicle,
                origin,
                ..
            } => {
                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.1 == VehicleType::Bike {
                    PathConstraints::Bike
                } else {
                    PathConstraints::Car
                };
                if goal.goal_pos(constraints, map).is_none() {
                    spec = TripSpec::NoRoomToSpawn {
                        i: map.get_l(start_pos.lane()).src_i,
                        goal: goal.clone(),
                        use_vehicle: use_vehicle.clone(),
                        origin: origin.clone(),
                        error: format!("goal_pos to {:?} for a {:?} failed", goal, constraints),
                    };
                }
            }
            TripSpec::NoRoomToSpawn { .. } => {}
            TripSpec::UsingParkedCar { .. } => {}
            TripSpec::JustWalking { start, goal, .. } => {
                if start == goal {
                    panic!(
                        "A trip just walking from {:?} to {:?} doesn't make sense",
                        start, goal
                    );
                }
            }
            TripSpec::UsingBike { start, goal, .. } => {
                // 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, _, off_map) => {
                        SidewalkSpot::end_at_border(*i, off_map.clone(), 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
                                );
                                spec = backup_plan.unwrap();
                            }
                        } else {
                            info!(
                                "Can't find biking connection for goal {}, walking instead",
                                b
                            );
                            spec = backup_plan.unwrap();
                        }
                    }
                } else if backup_plan.is_some() {
                    info!("Can't start biking from {}. Walking instead", start);
                    spec = backup_plan.unwrap();
                } else {
                    panic!(
                        "Can't start biking from {} and can't walk either! Goal is {:?}",
                        start, goal
                    );
                }
            }
            TripSpec::UsingTransit { .. } => {}
            TripSpec::Remote { .. } => {}
        };

        self.trips
            .push((person.id, start_time, spec, trip_start, cancelled, modified));
    }

    pub fn finalize(
        mut self,
        map: &Map,
        trips: &mut TripManager,
        scheduler: &mut Scheduler,
        timer: &mut Timer,
    ) {
        let pathfinding_upfront = trips.pathfinding_upfront;
        let profile = false;
        if profile {
            abstutil::start_profiler();
        }
        let paths = timer.parallelize(
            "calculate paths",
            Parallelism::Fastest,
            std::mem::replace(&mut self.trips, Vec::new()),
            |tuple| {
                let req = tuple.2.get_pathfinding_request(map);
                (
                    tuple,
                    req.clone(),
                    if pathfinding_upfront {
                        req.and_then(|r| map.pathfind(r))
                    } else {
                        None
                    },
                )
            },
        );
        if profile {
            abstutil::stop_profiler();
        }

        timer.start_iter("spawn trips", paths.len());
        for ((p, start_time, spec, trip_start, cancelled, modified), maybe_req, maybe_path) in paths
        {
            timer.next();

            // TODO clone() is super weird to do here, but we just need to make the borrow checker
            // happy. All we're doing is grabbing IDs off this.
            let person = trips.get_person(p).unwrap().clone();
            // Just create the trip for each case.
            // TODO Not happy about this clone()
            let trip = match spec.clone() {
                TripSpec::VehicleAppearing {
                    goal, use_vehicle, ..
                } => {
                    let mut legs = vec![TripLeg::Drive(use_vehicle, goal.clone())];
                    if let DrivingGoal::ParkNear(b) = goal {
                        legs.push(TripLeg::Walk(SidewalkSpot::building(b, map)));
                    }
                    trips.new_trip(
                        person.id,
                        start_time,
                        trip_start,
                        if use_vehicle.1 == VehicleType::Bike {
                            TripMode::Bike
                        } else {
                            TripMode::Drive
                        },
                        modified,
                        legs,
                        map,
                    )
                }
                TripSpec::NoRoomToSpawn {
                    goal, use_vehicle, ..
                } => {
                    let mut legs = vec![TripLeg::Drive(use_vehicle, goal.clone())];
                    if let DrivingGoal::ParkNear(b) = goal {
                        legs.push(TripLeg::Walk(SidewalkSpot::building(b, map)));
                    }
                    trips.new_trip(
                        person.id,
                        start_time,
                        trip_start,
                        if use_vehicle.1 == VehicleType::Bike {
                            TripMode::Bike
                        } else {
                            TripMode::Drive
                        },
                        modified,
                        legs,
                        map,
                    )
                }
                TripSpec::UsingParkedCar { car, goal, .. } => {
                    let mut legs = vec![
                        TripLeg::Walk(SidewalkSpot::deferred_parking_spot()),
                        TripLeg::Drive(car, goal.clone()),
                    ];
                    match goal {
                        DrivingGoal::ParkNear(b) => {
                            legs.push(TripLeg::Walk(SidewalkSpot::building(b, map)));
                        }
                        DrivingGoal::Border(_, _, _) => {}
                    }
                    trips.new_trip(
                        person.id,
                        start_time,
                        trip_start,
                        TripMode::Drive,
                        modified,
                        legs,
                        map,
                    )
                }
                TripSpec::JustWalking { goal, .. } => trips.new_trip(
                    person.id,
                    start_time,
                    trip_start,
                    TripMode::Walk,
                    modified,
                    vec![TripLeg::Walk(goal.clone())],
                    map,
                ),
                TripSpec::UsingBike { bike, start, goal } => {
                    let walk_to = SidewalkSpot::bike_rack(start, map).unwrap();
                    let mut legs = vec![
                        TripLeg::Walk(walk_to.clone()),
                        TripLeg::Drive(bike, goal.clone()),
                    ];
                    match goal {
                        DrivingGoal::ParkNear(b) => {
                            legs.push(TripLeg::Walk(SidewalkSpot::building(b, map)));
                        }
                        DrivingGoal::Border(_, _, _) => {}
                    };
                    trips.new_trip(
                        person.id,
                        start_time,
                        trip_start,
                        TripMode::Bike,
                        modified,
                        legs,
                        map,
                    )
                }
                TripSpec::UsingTransit {
                    route,
                    stop1,
                    maybe_stop2,
                    goal,
                    ..
                } => {
                    let walk_to = SidewalkSpot::bus_stop(stop1, map);
                    let legs = if let Some(stop2) = maybe_stop2 {
                        vec![
                            TripLeg::Walk(walk_to.clone()),
                            TripLeg::RideBus(route, Some(stop2)),
                            TripLeg::Walk(goal),
                        ]
                    } else {
                        vec![
                            TripLeg::Walk(walk_to.clone()),
                            TripLeg::RideBus(route, None),
                        ]
                    };
                    trips.new_trip(
                        person.id,
                        start_time,
                        trip_start,
                        TripMode::Transit,
                        modified,
                        legs,
                        map,
                    )
                }
                TripSpec::Remote { to, mode, .. } => trips.new_trip(
                    person.id,
                    start_time,
                    trip_start,
                    mode,
                    modified,
                    vec![TripLeg::Remote(to)],
                    map,
                ),
            };

            if cancelled {
                trips.cancel_trip(trip);
            } else {
                scheduler.push(
                    start_time,
                    Command::StartTrip(trip, spec, maybe_req, maybe_path),
                );
            }
        }
    }
}

impl TripSpec {
    pub(crate) fn get_pathfinding_request(&self, map: &Map) -> Option<PathRequest> {
        match self {
            TripSpec::VehicleAppearing {
                start_pos,
                goal,
                use_vehicle,
                ..
            } => {
                let constraints = if use_vehicle.1 == VehicleType::Bike {
                    PathConstraints::Bike
                } else {
                    PathConstraints::Car
                };
                Some(PathRequest {
                    start: *start_pos,
                    end: goal.goal_pos(constraints, map).unwrap(),
                    constraints,
                })
            }
            TripSpec::NoRoomToSpawn { .. } => None,
            // We don't know where the parked car will be
            TripSpec::UsingParkedCar { .. } => None,
            TripSpec::JustWalking { start, goal, .. } => Some(PathRequest {
                start: start.sidewalk_pos,
                end: goal.sidewalk_pos,
                constraints: PathConstraints::Pedestrian,
            }),
            TripSpec::UsingBike { start, .. } => Some(PathRequest {
                start: map.get_b(*start).sidewalk_pos,
                end: SidewalkSpot::bike_rack(*start, map).unwrap().sidewalk_pos,
                constraints: PathConstraints::Pedestrian,
            }),
            TripSpec::UsingTransit { start, stop1, .. } => Some(PathRequest {
                start: start.sidewalk_pos,
                end: SidewalkSpot::bus_stop(*stop1, map).sidewalk_pos,
                constraints: PathConstraints::Pedestrian,
            }),
            TripSpec::Remote { .. } => None,
        }
    }
}