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
use geom::{Distance, Duration, Polygon};
use map_model::NORMAL_LANE_THICKNESS;
use sim::{TripEndpoint, TripMode};
use widgetry::mapspace::{ObjectID, ToggleZoomed, World};
use widgetry::{
    Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Panel, State, Text,
    VerticalAlignment, Widget,
};

use super::Neighborhood;
use crate::app::{App, Transition};
use crate::common::{cmp_dist, cmp_duration, InputWaypoints, WaypointID};

pub struct RoutePlanner {
    panel: Panel,
    waypoints: InputWaypoints,
    world: World<ID>,

    neighborhood: Neighborhood,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum ID {
    RouteAfterFilters,
    RouteBeforeFilters,
    Waypoint(WaypointID),
}
impl ObjectID for ID {}

impl RoutePlanner {
    pub fn new_state(
        ctx: &mut EventCtx,
        app: &mut App,
        neighborhood: Neighborhood,
    ) -> Box<dyn State<App>> {
        let mut rp = RoutePlanner {
            panel: Panel::empty(ctx),
            waypoints: InputWaypoints::new(app),
            world: World::bounded(app.primary.map.get_bounds()),
            neighborhood,
        };
        rp.update(ctx, app);
        Box::new(rp)
    }

    fn update(&mut self, ctx: &mut EventCtx, app: &App) {
        self.panel = Panel::new_builder(Widget::col(vec![
            ctx.style()
                .btn_outline
                .text("Back to editing modal filters")
                .hotkey(Key::Escape)
                .build_def(ctx),
            Line("Warning: Time estimates assume freeflow conditions (no traffic)")
                .fg(Color::RED)
                .into_widget(ctx),
            self.waypoints.get_panel_widget(ctx),
        ]))
        .aligned(HorizontalAlignment::Left, VerticalAlignment::Top)
        // Hovering on waypoint cards
        .ignore_initial_events()
        .build(ctx);

        let mut world = self.calculate_paths(ctx, app);
        self.waypoints
            .rebuild_world(ctx, &mut world, ID::Waypoint, 2);
        world.initialize_hover(ctx);
        world.rebuilt_during_drag(&self.world);
        self.world = world;
    }

    fn calculate_paths(&self, ctx: &mut EventCtx, app: &App) -> World<ID> {
        let map = &app.primary.map;
        let mut world = World::bounded(map.get_bounds());

        // First the route respecting the filters
        let (total_time_after, total_dist_after) = {
            let mut params = map.routing_params().clone();
            params
                .avoid_roads
                .extend(app.session.modal_filters.roads.keys().cloned());
            let cache_custom = true;

            let mut draw_route = ToggleZoomed::builder();
            let mut hitbox_pieces = Vec::new();
            let mut total_time = Duration::ZERO;
            let mut total_dist = Distance::ZERO;
            for pair in self.waypoints.get_waypoints().windows(2) {
                if let Some((path, pl)) =
                    TripEndpoint::path_req(pair[0], pair[1], TripMode::Drive, map)
                        .and_then(|req| map.pathfind_with_params(req, &params, cache_custom).ok())
                        .and_then(|path| path.trace(map).map(|pl| (path, pl)))
                {
                    let shape = pl.make_polygons(5.0 * NORMAL_LANE_THICKNESS);
                    draw_route
                        .unzoomed
                        .push(Color::RED.alpha(0.8), shape.clone());
                    draw_route.zoomed.push(Color::RED.alpha(0.5), shape.clone());
                    hitbox_pieces.push(shape);

                    // Use estimate_duration and not the original cost from pathfinding, since that
                    // includes huge penalties when the route is forced to cross a filter
                    total_time += path.estimate_duration(map, None);
                    total_dist += path.total_length();
                }
            }
            if !hitbox_pieces.is_empty() {
                let mut txt = Text::new();
                txt.add_line(Line("Route respecting the new modal filters"));
                txt.add_line(Line(format!("Time: {}", total_time)));
                txt.add_line(Line(format!("Distance: {}", total_dist)));

                world
                    .add(ID::RouteAfterFilters)
                    .hitbox(Polygon::union_all(hitbox_pieces))
                    .zorder(0)
                    .draw(draw_route)
                    .hover_outline(Color::BLACK, Distance::meters(2.0))
                    .tooltip(txt)
                    .build(ctx);
            }

            (total_time, total_dist)
        };

        // Then the one ignoring filters
        {
            let mut draw_route = ToggleZoomed::builder();
            let mut hitbox_pieces = Vec::new();
            let mut total_time = Duration::ZERO;
            let mut total_dist = Distance::ZERO;
            for pair in self.waypoints.get_waypoints().windows(2) {
                if let Some((path, pl)) =
                    TripEndpoint::path_req(pair[0], pair[1], TripMode::Drive, map)
                        .and_then(|req| map.pathfind(req).ok())
                        .and_then(|path| path.trace(map).map(|pl| (path, pl)))
                {
                    let shape = pl.make_polygons(5.0 * NORMAL_LANE_THICKNESS);
                    draw_route
                        .unzoomed
                        .push(Color::BLUE.alpha(0.8), shape.clone());
                    draw_route
                        .zoomed
                        .push(Color::BLUE.alpha(0.5), shape.clone());
                    hitbox_pieces.push(shape);

                    total_time += path.estimate_duration(map, None);
                    total_dist += path.total_length();
                }
            }
            if !hitbox_pieces.is_empty() {
                let mut txt = Text::new();
                // If these two stats are the same, assume the two paths are equivalent
                if total_time == total_time_after && total_dist == total_dist_after {
                    world.delete(ID::RouteAfterFilters);
                    txt.add_line(Line(
                        "The route is the same before/after the new modal filters",
                    ));
                    txt.add_line(Line(format!("Time: {}", total_time)));
                    txt.add_line(Line(format!("Distance: {}", total_dist)));
                } else {
                    txt.add_line(Line("Route before the new modal filters"));
                    txt.add_line(Line(format!("Time: {}", total_time)));
                    txt.add_line(Line(format!("Distance: {}", total_dist)));
                    cmp_duration(
                        &mut txt,
                        app,
                        total_time - total_time_after,
                        "shorter",
                        "longer",
                    );
                    cmp_dist(
                        &mut txt,
                        app,
                        total_dist - total_dist_after,
                        "shorter",
                        "longer",
                    );
                }

                world
                    .add(ID::RouteBeforeFilters)
                    .hitbox(Polygon::union_all(hitbox_pieces))
                    // If the two routes partly overlap, put the "before" on top, since it has
                    // the comparison stats.
                    .zorder(1)
                    .draw(draw_route)
                    .hover_outline(Color::BLACK, Distance::meters(2.0))
                    .tooltip(txt)
                    .build(ctx);
            }
        }

        world
    }
}

impl State<App> for RoutePlanner {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        let world_outcome_for_waypoints = match self.world.event(ctx) {
            x => x.map_id(|id| match id {
                ID::Waypoint(id) => id,
                _ => unreachable!(),
            }),
        };

        let panel_outcome = self.panel.event(ctx);
        if let Outcome::Clicked(ref x) = panel_outcome {
            if x == "Back to editing modal filters" {
                // We'll cache a custom pathfinder per set of avoided roads. Avoid leaking memory
                // by clearing this out
                app.primary.map.clear_custom_pathfinder_cache();

                return Transition::ConsumeState(Box::new(|state, ctx, app| {
                    let state = state.downcast::<RoutePlanner>().ok().unwrap();
                    vec![super::viewer::Viewer::new_state(
                        ctx,
                        app,
                        state.neighborhood,
                    )]
                }));
            }
        }

        if self
            .waypoints
            .event(app, panel_outcome, world_outcome_for_waypoints)
        {
            self.update(ctx, app);
        }

        Transition::Keep
    }

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        self.panel.draw(g);

        g.redraw(&self.neighborhood.fade_irrelevant);
        g.redraw(&self.neighborhood.draw_filters);
        if g.canvas.is_unzoomed() {
            self.neighborhood.labels.draw(g, app);
        }

        self.world.draw(g);
    }
}