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
use std::collections::HashSet;

use geom::Distance;
use map_model::{IntersectionID, RoadID};
use widgetry::mapspace::{ObjectID, World, WorldOutcome};
use widgetry::{
    Color, EventCtx, GeomBatch, GfxCtx, Key, Outcome, Panel, State, Text, TextExt, Toggle, Widget,
};

use super::per_neighborhood::{Tab, TakeNeighborhood};
use super::{DiagonalFilter, Neighborhood};
use crate::app::{App, Transition};

pub struct Viewer {
    panel: Panel,
    neighborhood: Neighborhood,
    world: World<Obj>,
}

impl TakeNeighborhood for Viewer {
    fn take_neighborhood(self) -> Neighborhood {
        self.neighborhood
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Obj {
    InteriorRoad(RoadID),
    InteriorIntersection(IntersectionID),
}
impl ObjectID for Obj {}

impl Viewer {
    pub fn new_state(
        ctx: &mut EventCtx,
        app: &App,
        neighborhood: Neighborhood,
    ) -> Box<dyn State<App>> {
        let panel = Tab::Connectivity
            .panel_builder(
                ctx,
                app,
                Widget::col(vec![
                    Widget::row(vec![
                        "Draw traffic cells as".text_widget(ctx).centered_vert(),
                        Toggle::choice(ctx, "draw cells", "areas", "streets", Key::D, true),
                    ]),
                    "Click a road to add or remove a modal filter".text_widget(ctx),
                    Text::new().into_widget(ctx).named("warnings"),
                ]),
            )
            .build(ctx);

        let mut viewer = Viewer {
            panel,
            neighborhood,
            world: World::unbounded(),
        };
        viewer.neighborhood_changed(ctx, app);
        Box::new(viewer)
    }

    fn neighborhood_changed(&mut self, ctx: &mut EventCtx, app: &App) {
        self.world = make_world(
            ctx,
            app,
            &self.neighborhood,
            self.panel.is_checked("draw cells"),
        );
        let disconnected_cells = self
            .neighborhood
            .cells
            .iter()
            .filter(|c| c.borders.is_empty())
            .count();
        // TODO Also add a red outline to them or something
        let warning = if disconnected_cells == 0 {
            String::new()
        } else {
            format!("{} cells are totally disconnected", disconnected_cells)
        };
        self.panel
            .replace(ctx, "warnings", warning.text_widget(ctx));
    }
}

impl State<App> for Viewer {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        match self.panel.event(ctx) {
            Outcome::Clicked(x) => {
                return Tab::Connectivity.must_handle_action::<Viewer>(ctx, app, x.as_ref());
            }
            Outcome::Changed(_) => {
                self.world = make_world(
                    ctx,
                    app,
                    &self.neighborhood,
                    self.panel.is_checked("draw cells"),
                );
            }
            _ => {}
        }

        match self.world.event(ctx) {
            WorldOutcome::ClickedObject(Obj::InteriorRoad(r)) => {
                if app.session.modal_filters.roads.remove(&r).is_none() {
                    // Place the filter on the part of the road that was clicked
                    let road = app.primary.map.get_r(r);
                    // These calls shouldn't fail -- since we clicked a road, the cursor must be in
                    // map-space. And project_pt returns a point that's guaranteed to be on the
                    // polyline.
                    let cursor_pt = ctx.canvas.get_cursor_in_map_space().unwrap();
                    let pt_on_line = road.center_pts.project_pt(cursor_pt);
                    let (distance, _) = road.center_pts.dist_along_of_point(pt_on_line).unwrap();

                    app.session.modal_filters.roads.insert(r, distance);
                }
                // TODO The cell coloring changes quite spuriously just by toggling a filter, even
                // when it doesn't matter
                self.neighborhood =
                    Neighborhood::new(ctx, app, self.neighborhood.orig_perimeter.clone());
                self.neighborhood_changed(ctx, app);
            }
            WorldOutcome::ClickedObject(Obj::InteriorIntersection(i)) => {
                // Toggle through all possible filters
                let mut all = DiagonalFilter::filters_for(app, i);
                if let Some(current) = app.session.modal_filters.intersections.get(&i) {
                    let idx = all.iter().position(|x| x == current).unwrap();
                    if idx == all.len() - 1 {
                        app.session.modal_filters.intersections.remove(&i);
                    } else {
                        app.session
                            .modal_filters
                            .intersections
                            .insert(i, all.remove(idx + 1));
                    }
                } else if !all.is_empty() {
                    app.session
                        .modal_filters
                        .intersections
                        .insert(i, all.remove(0));
                }

                self.neighborhood =
                    Neighborhood::new(ctx, app, self.neighborhood.orig_perimeter.clone());
                self.neighborhood_changed(ctx, app);
            }
            _ => {}
        }

        Transition::Keep
    }

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        self.panel.draw(g);
        g.redraw(&self.neighborhood.fade_irrelevant);
        self.world.draw(g);
        self.neighborhood.draw_filters.draw(g);
        // TODO Since we cover such a small area, treating multiple segments of one road as the
        // same might be nice. And we should seed the quadtree with the locations of filters and
        // arrows, possibly.
        if g.canvas.is_unzoomed() {
            self.neighborhood.labels.draw(g, app);
        }
    }
}

fn make_world(
    ctx: &mut EventCtx,
    app: &App,
    neighborhood: &Neighborhood,
    draw_cells_as_areas: bool,
) -> World<Obj> {
    let map = &app.primary.map;
    let mut world = World::bounded(map.get_bounds());

    // Could refactor this, but I suspect we'll settle on one drawing style or another. Toggling
    // between the two is temporary.
    if draw_cells_as_areas {
        for r in &neighborhood.orig_perimeter.interior {
            world
                .add(Obj::InteriorRoad(*r))
                .hitbox(map.get_r(*r).get_thick_polygon())
                .drawn_in_master_batch()
                .hover_outline(Color::BLACK, Distance::meters(5.0))
                .clickable()
                .build(ctx);
        }

        world.draw_master_batch(ctx, super::draw_cells::draw_cells(map, neighborhood));
    } else {
        let mut draw_intersections = GeomBatch::new();
        let mut debug_cell_borders = GeomBatch::new();
        let mut seen_roads = HashSet::new();
        for (idx, cell) in neighborhood.cells.iter().enumerate() {
            let color = super::draw_cells::COLORS[idx % super::draw_cells::COLORS.len()].alpha(0.9);
            for r in cell.roads.keys() {
                // TODO Roads with a filter belong to two cells. Avoid adding them to the world
                // twice. But the drawn form (and the intersections included) needs to be adjusted
                // to use two colors.
                if seen_roads.contains(r) {
                    continue;
                }
                seen_roads.insert(*r);

                world
                    .add(Obj::InteriorRoad(*r))
                    .hitbox(map.get_r(*r).get_thick_polygon())
                    .draw_color(color)
                    .hover_outline(Color::BLACK, Distance::meters(5.0))
                    .clickable()
                    .build(ctx);
            }
            for i in
                crate::common::intersections_from_roads(&cell.roads.keys().cloned().collect(), map)
            {
                draw_intersections.push(color, map.get_i(i).polygon.clone());
            }
            // Draw the cell borders as outlines, for debugging. (Later, we probably want some kind
            // of arrow styling)
            for i in &cell.borders {
                if let Ok(p) = map.get_i(*i).polygon.to_outline(Distance::meters(2.0)) {
                    debug_cell_borders.push(color.alpha(1.0), p);
                }
            }
        }
        draw_intersections.append(debug_cell_borders);
        world.draw_master_batch(ctx, draw_intersections);
    }

    for i in &neighborhood.interior_intersections {
        let i = map.get_i(*i);
        if i.roads.len() != 4 {
            continue;
        }
        world
            .add(Obj::InteriorIntersection(i.id))
            .hitbox(i.polygon.clone())
            .drawn_in_master_batch()
            .hover_outline(Color::BLACK, Distance::meters(5.0))
            .clickable()
            .build(ctx);
    }

    world.initialize_hover(ctx);

    world
}