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
// The sim crate runs a traffic simulation on top of the map_model. See also
// https://dabreegster.github.io/abstreet/trafficsim/index.html.
//
// The simulation is very roughly layered into two pieces: the low-level "mechanics" of simulating
// individual agents over time, and higher-level systems like TripManager and TransitSimState that
// glue together individual goals executed by the agents.

#[macro_use]
extern crate log;

use std::fmt;

use serde::{Deserialize, Serialize};

use abstutil::{deserialize_usize, serialize_usize};
use geom::{Distance, Pt2D, Speed, Time};
use map_model::{
    BuildingID, BusRouteID, BusStopID, DirectedRoadID, IntersectionID, LaneID, Map, ParkingLotID,
    Path, PathConstraints, PathRequest, Position,
};

pub use self::analytics::{Analytics, TripPhase};
pub(crate) use self::cap::CapSimState;
pub(crate) use self::events::Event;
pub use self::events::{AlertLocation, TripPhaseType};
pub use self::make::{
    BorderSpawnOverTime, ExternalPerson, ExternalTrip, IndividTrip, OffMapLocation,
    OriginDestination, PersonSpec, Scenario, ScenarioGenerator, ScenarioModifier, SimFlags,
    SpawnOverTime, SpawnTrip, TripPurpose, TripSpawner, TripSpec,
};
pub(crate) use self::mechanics::{
    DrivingSimState, IntersectionSimState, ParkingSim, ParkingSimState, WalkingSimState,
};
pub(crate) use self::pandemic::PandemicModel;
pub(crate) use self::router::{ActionAtEnd, Router};
pub(crate) use self::scheduler::{Command, Scheduler};
pub use self::sim::{AgentProperties, AlertHandler, Sim, SimCallback, SimOptions};
pub(crate) use self::transit::TransitSimState;
pub use self::trips::{Person, PersonState, TripInfo, TripResult};
pub use self::trips::{TripEndpoint, TripMode};
pub(crate) use self::trips::{TripLeg, TripManager};
pub use crate::render::{
    CarStatus, DontDrawAgents, DrawCarInput, DrawPedCrowdInput, DrawPedestrianInput, GetDrawAgents,
    PedCrowdLocation, UnzoomedAgent,
};

mod analytics;
mod cap;
mod events;
mod make;
mod mechanics;
mod pandemic;
mod render;
mod router;
mod scheduler;
mod sim;
mod transit;
mod trips;

// http://pccsc.net/bicycle-parking-info/ says 68 inches, which is 1.73m
pub const BIKE_LENGTH: Distance = Distance::const_meters(1.8);
// These two must be < PARKING_SPOT_LENGTH
pub const MIN_CAR_LENGTH: Distance = Distance::const_meters(4.5);
pub const MAX_CAR_LENGTH: Distance = Distance::const_meters(6.5);
// Note this is more than MAX_CAR_LENGTH
pub const BUS_LENGTH: Distance = Distance::const_meters(12.5);
pub const LIGHT_RAIL_LENGTH: Distance = Distance::const_meters(60.0);

// At all speeds (including at rest), cars must be at least this far apart, measured from front of
// one car to the back of the other.
pub const FOLLOWING_DISTANCE: Distance = Distance::const_meters(1.0);

// When spawning at borders, start the front of the vehicle this far along and gradually appear.
// Getting too close to EPSILON_DIST can lead to get_draw_car having no geometry at all.
pub const SPAWN_DIST: Distance = Distance::const_meters(0.05);

// The numeric ID must be globally unique, without considering VehicleType. VehicleType is bundled
// for convenient debugging.
// TODO Implement Eq, Hash, Ord manually to guarantee this.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct CarID(
    #[serde(
        serialize_with = "serialize_usize",
        deserialize_with = "deserialize_usize"
    )]
    pub usize,
    pub VehicleType,
);

impl fmt::Display for CarID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.1 {
            VehicleType::Car => write!(f, "Car #{}", self.0),
            VehicleType::Bus => write!(f, "Bus #{}", self.0),
            VehicleType::Train => write!(f, "Train #{}", self.0),
            VehicleType::Bike => write!(f, "Bike #{}", self.0),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PedestrianID(
    #[serde(
        serialize_with = "serialize_usize",
        deserialize_with = "deserialize_usize"
    )]
    pub usize,
);

impl fmt::Display for PedestrianID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Pedestrian #{}", self.0)
    }
}

#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Hash)]
pub enum AgentID {
    Car(CarID),
    Pedestrian(PedestrianID),
    // TODO Rename...
    BusPassenger(PersonID, CarID),
}

impl AgentID {
    pub(crate) fn as_car(self) -> CarID {
        match self {
            AgentID::Car(id) => id,
            _ => panic!("Not a CarID: {:?}", self),
        }
    }

    pub fn to_type(self) -> AgentType {
        match self {
            AgentID::Car(c) => match c.1 {
                VehicleType::Car => AgentType::Car,
                VehicleType::Bike => AgentType::Bike,
                VehicleType::Bus => AgentType::Bus,
                VehicleType::Train => AgentType::Train,
            },
            AgentID::Pedestrian(_) => AgentType::Pedestrian,
            AgentID::BusPassenger(_, _) => AgentType::TransitRider,
        }
    }
}

impl fmt::Display for AgentID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AgentID::Car(id) => write!(f, "AgentID({})", id),
            AgentID::Pedestrian(id) => write!(f, "AgentID({})", id),
            AgentID::BusPassenger(person, bus) => write!(f, "AgentID({} on {})", person, bus),
        }
    }
}

#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Hash)]
pub enum AgentType {
    Car,
    Bike,
    Bus,
    Train,
    Pedestrian,
    TransitRider,
}

impl AgentType {
    pub fn all() -> Vec<AgentType> {
        vec![
            AgentType::Car,
            AgentType::Bike,
            AgentType::Bus,
            AgentType::Train,
            AgentType::Pedestrian,
            AgentType::TransitRider,
        ]
    }

    pub fn noun(self) -> &'static str {
        match self {
            AgentType::Car => "Car",
            AgentType::Bike => "Bike",
            AgentType::Bus => "Bus",
            AgentType::Train => "Train",
            AgentType::Pedestrian => "Pedestrian",
            AgentType::TransitRider => "Transit rider",
        }
    }

    pub fn plural_noun(self) -> &'static str {
        match self {
            AgentType::Car => "cars",
            AgentType::Bike => "bikes",
            AgentType::Bus => "buses",
            AgentType::Train => "trains",
            AgentType::Pedestrian => "pedestrians",
            AgentType::TransitRider => "transit riders",
        }
    }

    pub fn ongoing_verb(self) -> &'static str {
        match self {
            AgentType::Car => "driving",
            AgentType::Bike => "biking",
            AgentType::Bus | AgentType::Train => unreachable!(),
            AgentType::Pedestrian => "walking",
            AgentType::TransitRider => "riding transit",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct TripID(
    #[serde(
        serialize_with = "serialize_usize",
        deserialize_with = "deserialize_usize"
    )]
    pub usize,
);

impl fmt::Display for TripID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Trip #{}", self.0)
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PersonID(
    #[serde(
        serialize_with = "serialize_usize",
        deserialize_with = "deserialize_usize"
    )]
    pub usize,
);

impl fmt::Display for PersonID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Person {}", self.0)
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct OrigPersonID(
    #[serde(
        serialize_with = "serialize_usize",
        deserialize_with = "deserialize_usize"
    )]
    pub usize,
    #[serde(
        serialize_with = "serialize_usize",
        deserialize_with = "deserialize_usize"
    )]
    pub usize,
);

#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
pub enum VehicleType {
    Car,
    Bus,
    Train,
    Bike,
}

impl fmt::Display for VehicleType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            VehicleType::Car => write!(f, "car"),
            VehicleType::Bus => write!(f, "bus"),
            VehicleType::Train => write!(f, "train"),
            VehicleType::Bike => write!(f, "bike"),
        }
    }
}

impl VehicleType {
    pub fn to_constraints(self) -> PathConstraints {
        match self {
            VehicleType::Car => PathConstraints::Car,
            VehicleType::Bus => PathConstraints::Bus,
            VehicleType::Train => PathConstraints::Train,
            VehicleType::Bike => PathConstraints::Bike,
        }
    }

    pub(crate) fn is_transit(self) -> bool {
        match self {
            VehicleType::Car => false,
            VehicleType::Bus => true,
            VehicleType::Train => true,
            VehicleType::Bike => false,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Vehicle {
    pub id: CarID,
    pub owner: Option<PersonID>,
    pub vehicle_type: VehicleType,
    pub length: Distance,
    pub max_speed: Option<Speed>,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct VehicleSpec {
    pub vehicle_type: VehicleType,
    pub length: Distance,
    pub max_speed: Option<Speed>,
}

impl VehicleSpec {
    pub fn make(self, id: CarID, owner: Option<PersonID>) -> Vehicle {
        assert_eq!(id.1, self.vehicle_type);
        Vehicle {
            id,
            owner,
            vehicle_type: self.vehicle_type,
            length: self.length,
            max_speed: self.max_speed,
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum ParkingSpot {
    // Lane and idx
    Onstreet(LaneID, usize),
    // Building and idx (pretty meaningless)
    Offstreet(BuildingID, usize),
    Lot(ParkingLotID, usize),
}

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct ParkedCar {
    pub vehicle: Vehicle,
    pub spot: ParkingSpot,
    pub parked_since: Time,
}

// It'd be nice to inline the goal_pos like SidewalkSpot does, but DrivingGoal is persisted in
// Scenarios, so this wouldn't survive map edits.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum DrivingGoal {
    ParkNear(BuildingID),
    Border(IntersectionID, LaneID, Option<OffMapLocation>),
}

impl DrivingGoal {
    pub fn end_at_border(
        dr: DirectedRoadID,
        constraints: PathConstraints,
        destination: Option<OffMapLocation>,
        map: &Map,
    ) -> Option<DrivingGoal> {
        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], destination))
        }
    }

    pub fn goal_pos(&self, constraints: PathConstraints, map: &Map) -> Option<Position> {
        match self {
            DrivingGoal::ParkNear(b) => match constraints {
                PathConstraints::Car => {
                    Some(Position::start(map.find_driving_lane_near_building(*b)))
                }
                PathConstraints::Bike => Some(map.get_b(*b).biking_connection(map)?.0),
                PathConstraints::Bus | PathConstraints::Train | PathConstraints::Pedestrian => {
                    unreachable!()
                }
            },
            DrivingGoal::Border(_, l, _) => Some(Position::end(*l, map)),
        }
    }

    pub(crate) fn make_router(&self, owner: CarID, path: Path, map: &Map) -> Router {
        match self {
            DrivingGoal::ParkNear(b) => {
                if owner.1 == VehicleType::Bike {
                    Router::bike_then_stop(owner, path, SidewalkSpot::bike_rack(*b, map).unwrap())
                } else {
                    Router::park_near(owner, path, *b)
                }
            }
            DrivingGoal::Border(i, last_lane, _) => {
                Router::end_at_border(owner, path, map.get_l(*last_lane).length(), *i)
            }
        }
    }

    pub fn pt(&self, map: &Map) -> Pt2D {
        match self {
            DrivingGoal::ParkNear(b) => map.get_b(*b).polygon.center(),
            DrivingGoal::Border(i, _, _) => map.get_i(*i).polygon.center(),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct SidewalkSpot {
    pub connection: SidewalkPOI,
    pub sidewalk_pos: Position,
}

// Point of interest, that is
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum SidewalkPOI {
    // Note that for offstreet parking, the path will be the same as the building's front path.
    ParkingSpot(ParkingSpot),
    // Don't actually know where this goes yet!
    DeferredParkingSpot,
    Building(BuildingID),
    BusStop(BusStopID),
    Border(IntersectionID, Option<OffMapLocation>),
    // The bikeable position
    BikeRack(Position),
    SuddenlyAppear,
}

impl SidewalkSpot {
    // Pretty hacky case
    pub fn deferred_parking_spot() -> SidewalkSpot {
        SidewalkSpot {
            connection: SidewalkPOI::DeferredParkingSpot,
            // Dummy value
            sidewalk_pos: Position::start(LaneID(0)),
        }
    }

    pub fn parking_spot(
        spot: ParkingSpot,
        map: &Map,
        parking_sim: &ParkingSimState,
    ) -> SidewalkSpot {
        SidewalkSpot {
            connection: SidewalkPOI::ParkingSpot(spot),
            sidewalk_pos: parking_sim.spot_to_sidewalk_pos(spot, map),
        }
    }

    pub fn building(b: BuildingID, map: &Map) -> SidewalkSpot {
        SidewalkSpot {
            connection: SidewalkPOI::Building(b),
            sidewalk_pos: map.get_b(b).sidewalk_pos,
        }
    }

    // TODO For the case when we have to start/stop biking somewhere else, this won't match up with
    // a building though!
    pub fn bike_rack(b: BuildingID, map: &Map) -> Option<SidewalkSpot> {
        let (bike_pos, sidewalk_pos) = map.get_b(b).biking_connection(map)?;
        Some(SidewalkSpot {
            connection: SidewalkPOI::BikeRack(bike_pos),
            sidewalk_pos,
        })
    }

    pub fn bus_stop(stop: BusStopID, map: &Map) -> SidewalkSpot {
        SidewalkSpot {
            sidewalk_pos: map.get_bs(stop).sidewalk_pos,
            connection: SidewalkPOI::BusStop(stop),
        }
    }

    // Recall sidewalks are bidirectional.
    pub fn start_at_border(
        i: IntersectionID,
        origin: Option<OffMapLocation>,
        map: &Map,
    ) -> Option<SidewalkSpot> {
        let lanes = map
            .get_i(i)
            .get_outgoing_lanes(map, PathConstraints::Pedestrian);
        if !lanes.is_empty() {
            return Some(SidewalkSpot {
                sidewalk_pos: Position::start(lanes[0]),
                connection: SidewalkPOI::Border(i, origin),
            });
        }

        map.get_i(i)
            .get_incoming_lanes(map, PathConstraints::Pedestrian)
            .get(0)
            .map(|l| SidewalkSpot {
                sidewalk_pos: Position::end(*l, map),
                connection: SidewalkPOI::Border(i, origin),
            })
    }

    pub fn end_at_border(
        i: IntersectionID,
        destination: Option<OffMapLocation>,
        map: &Map,
    ) -> Option<SidewalkSpot> {
        if let Some(l) = map
            .get_i(i)
            .get_incoming_lanes(map, PathConstraints::Pedestrian)
            .get(0)
        {
            return Some(SidewalkSpot {
                sidewalk_pos: Position::end(*l, map),
                connection: SidewalkPOI::Border(i, destination),
            });
        }

        let lanes = map
            .get_i(i)
            .get_outgoing_lanes(map, PathConstraints::Pedestrian);
        if lanes.is_empty() {
            return None;
        }
        Some(SidewalkSpot {
            sidewalk_pos: Position::start(lanes[0]),
            connection: SidewalkPOI::Border(i, destination),
        })
    }

    pub fn suddenly_appear(l: LaneID, dist: Distance, map: &Map) -> SidewalkSpot {
        let lane = map.get_l(l);
        assert!(lane.is_walkable());
        assert!(dist <= lane.length());
        SidewalkSpot {
            sidewalk_pos: Position::new(l, dist),
            connection: SidewalkPOI::SuddenlyAppear,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct TimeInterval {
    // TODO Private fields
    pub start: Time,
    pub end: Time,
}

impl TimeInterval {
    pub fn new(start: Time, end: Time) -> TimeInterval {
        if end < start {
            panic!("Bad TimeInterval {} .. {}", start, end);
        }
        TimeInterval { start, end }
    }

    pub fn percent(&self, t: Time) -> f64 {
        if self.start == self.end {
            return 1.0;
        }

        let x = (t - self.start) / (self.end - self.start);
        assert!(x >= 0.0 && x <= 1.0);
        x
    }

    pub fn percent_clamp_end(&self, t: Time) -> f64 {
        if t > self.end {
            return 1.0;
        }
        self.percent(t)
    }
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct DistanceInterval {
    // TODO Private fields
    pub start: Distance,
    pub end: Distance,
}

impl DistanceInterval {
    pub fn new_driving(start: Distance, end: Distance) -> DistanceInterval {
        if end < start {
            panic!("Bad DistanceInterval {} .. {}", start, end);
        }
        DistanceInterval { start, end }
    }

    pub fn new_walking(start: Distance, end: Distance) -> DistanceInterval {
        // start > end is fine, might be contraflow.
        DistanceInterval { start, end }
    }

    pub fn lerp(&self, x: f64) -> Distance {
        assert!(x >= 0.0 && x <= 1.0);
        self.start + x * (self.end - self.start)
    }

    pub fn length(&self) -> Distance {
        (self.end - self.start).abs()
    }
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct CreatePedestrian {
    pub id: PedestrianID,
    pub start: SidewalkSpot,
    pub speed: Speed,
    pub goal: SidewalkSpot,
    pub req: PathRequest,
    pub path: Path,
    pub trip: TripID,
    pub person: PersonID,
}

#[derive(Serialize, Deserialize, PartialEq, Clone, Debug)]
pub struct CreateCar {
    pub vehicle: Vehicle,
    pub router: Router,
    pub req: PathRequest,
    pub start_dist: Distance,
    pub maybe_parked_car: Option<ParkedCar>,
    // None for buses
    pub trip_and_person: Option<(TripID, PersonID)>,
    pub maybe_route: Option<BusRouteID>,
}

impl CreateCar {
    pub fn for_appearing(
        vehicle: Vehicle,
        start_pos: Position,
        router: Router,
        req: PathRequest,
        trip: TripID,
        person: PersonID,
    ) -> CreateCar {
        CreateCar {
            vehicle,
            router,
            req,
            start_dist: start_pos.dist_along(),
            maybe_parked_car: None,
            trip_and_person: Some((trip, person)),
            maybe_route: None,
        }
    }

    // TODO Maybe inline in trips, the only caller.
    pub fn for_parked_car(
        parked_car: ParkedCar,
        router: Router,
        req: PathRequest,
        start_dist: Distance,
        trip: TripID,
        person: PersonID,
    ) -> CreateCar {
        CreateCar {
            vehicle: parked_car.vehicle.clone(),
            router,
            req,
            start_dist,
            maybe_parked_car: Some(parked_car),
            trip_and_person: Some((trip, person)),
            maybe_route: None,
        }
    }
}