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
use std::collections::{BTreeMap, BTreeSet};

use abstutil::Timer;
use geom::Distance;
use map_model::osm::RoadRank;
use map_model::{Block, Perimeter};
use widgetry::mapspace::{ObjectID, World, WorldOutcome};
use widgetry::{
    Color, Drawable, EventCtx, GeomBatch, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Panel,
    SimpleState, State, Text, TextExt, VerticalAlignment, Widget,
};

use crate::app::{App, Transition};
use crate::debug::polygons;

const COLORS: [Color; 6] = [
    Color::BLUE,
    Color::YELLOW,
    Color::GREEN,
    Color::PURPLE,
    Color::PINK,
    Color::ORANGE,
];
const MODIFIED: Color = Color::RED;
const TO_MERGE: Color = Color::CYAN;

pub struct Blockfinder {
    panel: Panel,
    id_counter: usize,
    blocks: BTreeMap<Obj, Block>,
    world: World<Obj>,
    to_merge: BTreeSet<Obj>,

    // Since we can't easily color adjacent groups of blocks differently when we classify but don't
    // merge, just remember the groups here
    partitions: Vec<Vec<Obj>>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Obj(usize);
impl ObjectID for Obj {}

impl Blockfinder {
    pub fn new_state(ctx: &mut EventCtx, app: &App) -> Box<dyn State<App>> {
        let mut state = Blockfinder {
            panel: make_panel(ctx),
            id_counter: 0,
            blocks: BTreeMap::new(),
            world: World::bounded(app.primary.map.get_bounds()),
            to_merge: BTreeSet::new(),

            partitions: Vec::new(),
        };

        ctx.loading_screen("calculate all blocks", |ctx, timer| {
            timer.start("find single blocks");
            let perimeters = Perimeter::find_all_single_blocks(&app.primary.map);
            timer.stop("find single blocks");
            state.add_blocks_with_coloring(ctx, app, perimeters, timer);
        });
        state.world.initialize_hover(ctx);
        Box::new(state)
    }

    fn new_id(&mut self) -> Obj {
        let id = Obj(self.id_counter);
        self.id_counter += 1;
        id
    }

    fn add_block(&mut self, ctx: &mut EventCtx, app: &App, id: Obj, color: Color, block: Block) {
        // Label the order of the perimeter roads while hovering
        let mut hovered = GeomBatch::from(vec![(color.alpha(0.5), block.polygon.clone())]);
        if let Ok(outline) = block.polygon.to_outline(Distance::meters(5.0)) {
            hovered.push(Color::BLACK, outline);
        }
        for (idx, id) in block.perimeter.roads.iter().enumerate().skip(1) {
            hovered.append(
                Text::from(Line(format!("{}", idx)).fg(Color::RED))
                    .bg(Color::BLACK)
                    .render_autocropped(ctx)
                    .scale(1.0)
                    .centered_on(
                        id.get_outermost_lane(&app.primary.map)
                            .lane_center_pts
                            .middle(),
                    ),
            );
        }

        let mut obj = self
            .world
            .add(id)
            .hitbox(block.polygon.clone())
            .draw_color(color.alpha(0.5))
            .draw_hovered(hovered)
            .clickable();
        if self.to_merge.contains(&id) {
            obj = obj.hotkey(Key::Space, "remove from merge set")
        } else {
            obj = obj.hotkey(Key::Space, "add to merge set")
        }
        obj.build(ctx);
        self.blocks.insert(id, block);
    }

    fn add_blocks_with_coloring(
        &mut self,
        ctx: &mut EventCtx,
        app: &App,
        perimeters: Vec<Perimeter>,
        timer: &mut Timer,
    ) {
        let mut colors = Perimeter::calculate_coloring(&perimeters, COLORS.len())
            .unwrap_or_else(|| (0..perimeters.len()).collect());

        timer.start_iter("blockify", perimeters.len());
        let mut blocks = Vec::new();
        for perimeter in perimeters {
            timer.next();
            match perimeter.to_block(&app.primary.map) {
                Ok(block) => {
                    blocks.push(block);
                }
                Err(err) => {
                    warn!("Failed to make a block from a perimeter: {}", err);
                    // We assigned a color, so don't let the indices get out of sync!
                    colors.remove(blocks.len());
                }
            }
        }

        for (block, color_idx) in blocks.into_iter().zip(colors.into_iter()) {
            let id = self.new_id();
            self.add_block(ctx, app, id, COLORS[color_idx % COLORS.len()], block);
        }
    }
}

impl State<App> for Blockfinder {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        if let Outcome::Clicked(x) = self.panel.event(ctx) {
            match x.as_ref() {
                "close" => {
                    return Transition::Pop;
                }
                "Merge" => {
                    // TODO We could update the panel, but meh
                    let mut perimeters = Vec::new();
                    for id in std::mem::take(&mut self.to_merge) {
                        perimeters.push(self.blocks.remove(&id).unwrap().perimeter);
                        // TODO If we happen to be hovering on one, uh oh! It's going to change
                        // ID...
                        self.world.delete(id);
                    }
                    let results = Perimeter::merge_all(perimeters, true);
                    let debug = results.len() > 1;
                    for perimeter in results {
                        let id = self.new_id();
                        let block = perimeter
                            .to_block(&app.primary.map)
                            .expect("Merged perimeter broke the polygon");
                        // To make the one-merge-at-a-time debugging easier, keep these in the
                        // merge set
                        if debug {
                            self.to_merge.insert(id);
                            self.add_block(ctx, app, id, TO_MERGE, block);
                        } else {
                            self.add_block(ctx, app, id, MODIFIED, block);
                        }
                    }
                    return Transition::Keep;
                }
                "Collapse dead-ends" => {
                    for id in std::mem::take(&mut self.to_merge) {
                        let mut perimeter = self.blocks.remove(&id).unwrap().perimeter;
                        perimeter.collapse_deadends();
                        let block = perimeter
                            .to_block(&app.primary.map)
                            .expect("collapsing deadends broke the polygon shape");
                        self.world.delete_before_replacement(id);
                        // We'll lose the original coloring, oh well
                        self.add_block(ctx, app, id, MODIFIED, block);
                    }
                }
                "Classify neighborhoods (but don't merge)" | "Auto-merge all neighborhoods" => {
                    let perimeters: Vec<Perimeter> = std::mem::take(&mut self.blocks)
                        .into_iter()
                        .map(|(_, b)| b.perimeter)
                        .collect();
                    let map = &app.primary.map;
                    let partitions = Perimeter::partition_by_predicate(perimeters, |r| {
                        // "Interior" roads of a neighborhood aren't classified as arterial
                        let road = map.get_r(r);
                        road.get_rank() == RoadRank::Local
                    });

                    // Reset pretty much all of our state
                    self.id_counter = 0;
                    self.world = World::bounded(app.primary.map.get_bounds());
                    self.to_merge.clear();
                    self.partitions = Vec::new();

                    if x == "Auto-merge all neighborhoods" {
                        // Actually merge the partitions
                        let mut merged = Vec::new();
                        for perimeters in partitions {
                            // If we got more than one result back, merging partially failed. Oh
                            // well?
                            merged.extend(Perimeter::merge_all(perimeters, false));
                        }
                        self.add_blocks_with_coloring(ctx, app, merged, &mut Timer::throwaway());
                    } else {
                        // Until we can actually do the merge, just color the partition to show
                        // results. The coloring is half-useless; adjacent partitions might be the
                        // same.
                        for (color_idx, perimeters) in partitions.into_iter().enumerate() {
                            let color = COLORS[color_idx % COLORS.len()];
                            let mut group = Vec::new();
                            for perimeter in perimeters {
                                if let Ok(block) = perimeter.to_block(map) {
                                    let id = self.new_id();
                                    self.add_block(ctx, app, id, color, block);
                                    group.push(id);
                                }
                            }
                            self.partitions.push(group);
                        }
                    }
                }
                "Reset" => {
                    return Transition::Replace(Blockfinder::new_state(ctx, app));
                }
                _ => unreachable!(),
            }
        }

        match self.world.event(ctx) {
            WorldOutcome::Keypress("add to merge set", id) => {
                self.to_merge.insert(id);
                let block = self.blocks.remove(&id).unwrap();
                self.world.delete_before_replacement(id);
                self.add_block(ctx, app, id, TO_MERGE, block);
            }
            WorldOutcome::Keypress("remove from merge set", id) => {
                self.to_merge.remove(&id);
                let block = self.blocks.remove(&id).unwrap();
                self.world.delete_before_replacement(id);
                // We'll lose the original coloring, oh well
                self.add_block(ctx, app, id, MODIFIED, block);
            }
            WorldOutcome::ClickedObject(id) => {
                return Transition::Push(OneBlock::new_state(ctx, app, self.blocks[&id].clone()));
            }
            _ => {}
        }

        if ctx.redo_mouseover() {
            if ctx.is_key_down(Key::LeftControl) {
                if let Some(id) = self.world.get_hovering() {
                    if !self.to_merge.contains(&id) {
                        self.to_merge.insert(id);
                        let block = self.blocks.remove(&id).unwrap();
                        self.world.delete_before_replacement(id);
                        self.add_block(ctx, app, id, TO_MERGE, block);
                    }
                }
            }
        }

        Transition::Keep
    }

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

        // If we've partitioned by neighborhood but not merged, show the grouping when hovering
        if let Some(id) = self.world.get_hovering() {
            let mut batch = GeomBatch::new();
            for group in &self.partitions {
                if group.contains(&id) {
                    for block in group {
                        batch.push(Color::RED.alpha(0.5), self.blocks[block].polygon.clone());
                    }
                    break;
                }
            }
            batch.draw(g);
        }
    }
}

pub struct OneBlock {
    block: Block,
    draw: Drawable,
}

impl OneBlock {
    pub fn new_state(ctx: &mut EventCtx, app: &App, block: Block) -> Box<dyn State<App>> {
        let mut batch = GeomBatch::new();
        batch.push(Color::RED.alpha(0.5), block.polygon.clone());
        for r in &block.perimeter.interior {
            batch.push(
                Color::CYAN.alpha(0.5),
                app.primary.map.get_r(*r).get_thick_polygon(),
            );
        }

        let panel = Panel::new_builder(Widget::col(vec![
            Widget::row(vec![
                Line("Blockfinder").small_heading().into_widget(ctx),
                ctx.style().btn_close_widget(ctx),
            ]),
            "You can also hold LCtrl to quickly highlight".text_widget(ctx),
            ctx.style()
                .btn_outline
                .text("Show perimeter in order")
                .hotkey(Key::O)
                .build_def(ctx),
            ctx.style()
                .btn_outline
                .text("Debug polygon")
                .hotkey(Key::D)
                .build_def(ctx),
        ]))
        .aligned(HorizontalAlignment::Center, VerticalAlignment::Top)
        .build(ctx);
        <dyn SimpleState<_>>::new_state(
            panel,
            Box::new(OneBlock {
                block,
                draw: batch.upload(ctx),
            }),
        )
    }
}

impl SimpleState<App> for OneBlock {
    fn on_click(&mut self, ctx: &mut EventCtx, app: &mut App, x: &str, _: &Panel) -> Transition {
        match x {
            "close" => Transition::Pop,
            "Show perimeter in order" => {
                let mut items = Vec::new();
                let map = &app.primary.map;
                for road_side in &self.block.perimeter.roads {
                    let lane = road_side.get_outermost_lane(map);
                    items.push(polygons::Item::Polygon(lane.get_thick_polygon()));
                }
                return Transition::Push(polygons::PolygonDebugger::new_state(
                    ctx,
                    "side of road",
                    items,
                    None,
                ));
            }
            "Debug polygon" => {
                return Transition::Push(polygons::PolygonDebugger::new_state(
                    ctx,
                    "pt",
                    self.block
                        .polygon
                        .clone()
                        .into_points()
                        .into_iter()
                        .map(polygons::Item::Point)
                        .collect(),
                    None,
                ));
            }
            _ => unreachable!(),
        }
    }

    fn other_event(&mut self, ctx: &mut EventCtx, _: &mut App) -> Transition {
        ctx.canvas_movement();
        Transition::Keep
    }

    fn draw(&self, g: &mut GfxCtx, _: &App) {
        g.redraw(&self.draw);
    }
}

fn make_panel(ctx: &mut EventCtx) -> Panel {
    Panel::new_builder(Widget::col(vec![
        Widget::row(vec![
            Line("Blockfinder").small_heading().into_widget(ctx),
            ctx.style().btn_close_widget(ctx),
        ]),
        "Click a block to examine.".text_widget(ctx),
        "Press space to mark/unmark for merging".text_widget(ctx),
        ctx.style()
            .btn_outline
            .text("Merge")
            .hotkey(Key::M)
            .build_def(ctx),
        ctx.style()
            .btn_outline
            .text("Collapse dead-ends")
            .hotkey(Key::D)
            .build_def(ctx),
        ctx.style()
            .btn_outline
            .text("Classify neighborhoods (but don't merge)")
            .hotkey(Key::C)
            .build_def(ctx),
        ctx.style()
            .btn_outline
            .text("Auto-merge all neighborhoods")
            .hotkey(Key::A)
            .build_def(ctx),
        ctx.style()
            .btn_solid_destructive
            .text("Reset")
            .build_def(ctx),
    ]))
    .aligned(HorizontalAlignment::Left, VerticalAlignment::Top)
    .build(ctx)
}