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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
use anyhow::Result;
use maplit::btreeset;

use abstutil::prettyprint_usize;
use geom::{Circle, Distance, Pt2D, Time};
use map_gui::colors::ColorSchemeChoice;
use map_gui::load::{FileLoader, MapLoader};
use map_gui::options::OptionsPanel;
use map_gui::render::{unzoomed_agent_radius, UnzoomedAgents};
use map_gui::tools::{ChooseSomething, Minimap, PopupMsg, TurnExplorer};
use map_gui::{AppLike, ID};
use sim::{Analytics, Scenario};
use widgetry::{
    lctrl, Choice, Color, EventCtx, GeomBatch, GfxCtx, HorizontalAlignment, Image, Key, Line,
    Outcome, Panel, State, StyledButtons, Text, TextExt, UpdateType, VerticalAlignment, Widget,
};

pub use self::gameplay::{spawn_agents_around, GameplayMode, TutorialPointer, TutorialState};
use self::misc_tools::{RoutePreview, TrafficRecorder};
pub use self::speed::{SpeedControls, TimePanel};
pub use self::time_warp::TimeWarpScreen;
use crate::app::{App, Transition};
use crate::common::{tool_panel, update_url_cam, CommonState, MinimapController};
use crate::debug::DebugMode;
use crate::edit::{
    can_edit_lane, EditMode, LaneEditor, SaveEdits, StopSignEditor, TrafficSignalEditor,
};
use crate::info::ContextualActions;
use crate::layer::favorites::{Favorites, ShowFavorites};
use crate::layer::PickLayer;
use crate::pregame::MainMenu;

pub mod dashboards;
pub mod gameplay;
mod misc_tools;
mod speed;
mod time_warp;
mod uber_turns;

pub struct SandboxMode {
    gameplay: Box<dyn gameplay::GameplayState>,
    pub gameplay_mode: GameplayMode,

    pub controls: SandboxControls,

    recalc_unzoomed_agent: Option<Time>,
    last_cs: ColorSchemeChoice,
}

pub struct SandboxControls {
    pub common: Option<CommonState>,
    route_preview: Option<RoutePreview>,
    tool_panel: Option<Panel>,
    time_panel: Option<TimePanel>,
    speed: Option<SpeedControls>,
    pub agent_meter: Option<AgentMeter>,
    minimap: Option<Minimap<App, MinimapController>>,
}

impl SandboxMode {
    /// If you don't need to chain any transitions after the SandboxMode that rely on its resources
    /// being loaded, use this. Otherwise, see `async_new`.
    pub fn simple_new(app: &mut App, mode: GameplayMode) -> Box<dyn State<App>> {
        SandboxMode::async_new(app, mode, Box::new(|_, _| Vec::new()))
    }

    /// This does not immediately initialize anything (like loading the correct map, instantiating
    /// the scenario, etc). That means if you're chaining this call with other transitions, you
    /// probably need to defer running them using `finalize`.
    pub fn async_new(
        app: &mut App,
        mode: GameplayMode,
        finalize: Box<dyn FnOnce(&mut EventCtx, &mut App) -> Vec<Transition>>,
    ) -> Box<dyn State<App>> {
        app.primary.clear_sim();
        Box::new(SandboxLoader {
            stage: Some(LoadStage::LoadingMap),
            mode,
            finalize: Some(finalize),
        })
    }

    // Just for Warping
    pub fn contextual_actions(&self) -> Actions {
        Actions {
            is_paused: self
                .controls
                .speed
                .as_ref()
                .map(|s| s.is_paused())
                .unwrap_or(true),
            can_interact: self.gameplay.can_examine_objects(),
            gameplay: self.gameplay_mode.clone(),
        }
    }
}

impl State<App> for SandboxMode {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        if app.opts.toggle_day_night_colors {
            if is_daytime(app) {
                app.change_color_scheme(ctx, ColorSchemeChoice::DayMode)
            } else {
                app.change_color_scheme(ctx, ColorSchemeChoice::NightMode)
            };
        }

        if app.opts.color_scheme != self.last_cs {
            self.last_cs = app.opts.color_scheme;
            self.controls.recreate_panels(ctx, app);
            self.gameplay.recreate_panels(ctx, app);
        }

        // Do this before gameplay
        if self.gameplay.can_move_canvas() {
            if ctx.canvas_movement() {
                if let Err(err) = update_url_cam(calculate_camera_center(ctx, app)) {
                    warn!("Couldn't update URL: {}", err);
                }
            }
        }

        let mut actions = self.contextual_actions();
        if let Some(t) = self
            .gameplay
            .event(ctx, app, &mut self.controls, &mut actions)
        {
            return t;
        }

        if ctx.redo_mouseover() {
            app.recalculate_current_selection(ctx);
        }

        // Order here is pretty arbitrary
        if app.opts.dev && ctx.input.pressed(lctrl(Key::D)) {
            return Transition::Push(DebugMode::new(ctx));
        }

        if let Some(ref mut m) = self.controls.minimap {
            if let Some(t) = m.event(ctx, app) {
                return t;
            }
            if let Some(t) = PickLayer::update(ctx, app, m.get_panel()) {
                return t;
            }
        }

        if let Some(ref mut s) = self.controls.speed {
            if let Some(t) = s.event(ctx, app, Some(&self.gameplay_mode)) {
                return t;
            }
        }

        // We need to recalculate unzoomed agent mouseover when the mouse is still and time passes
        // (since something could move beneath the cursor), or when the mouse moves.
        if app.primary.current_selection.is_none()
            && ctx.canvas.cam_zoom < app.opts.min_zoom_for_detail
        {
            if ctx.redo_mouseover()
                || self
                    .recalc_unzoomed_agent
                    .map(|t| t != app.primary.sim.time())
                    .unwrap_or(true)
            {
                mouseover_unzoomed_agent_circle(ctx, app);
            }
        }

        if let Some(ref mut r) = self.controls.route_preview {
            if let Some(t) = r.event(ctx, app) {
                return t;
            }
        }

        // Fragile ordering. Let this work before tool_panel, so Key::Escape from the info panel
        // beats the one to quit. And let speed update the sim before we update the info panel.
        if let Some(ref mut c) = self.controls.common {
            if let Some(t) = c.event(ctx, app, &mut actions) {
                return t;
            }
        }

        if let Some(ref mut tp) = self.controls.time_panel {
            tp.event(ctx, app);
        }

        if let Some(ref mut tp) = self.controls.tool_panel {
            match tp.event(ctx) {
                Outcome::Clicked(x) => match x.as_ref() {
                    "back" => {
                        return maybe_exit_sandbox(ctx);
                    }
                    "settings" => {
                        return Transition::Push(OptionsPanel::new(ctx, app));
                    }
                    _ => unreachable!(),
                },
                _ => {}
            }
        }
        if let Some(ref mut am) = self.controls.agent_meter {
            if let Some(t) = am.event(ctx, app) {
                return t;
            }
        }

        if self
            .controls
            .speed
            .as_ref()
            .map(|s| s.is_paused())
            .unwrap_or(true)
        {
            Transition::Keep
        } else {
            ctx.request_update(UpdateType::Game);
            Transition::Keep
        }
    }

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        if let Some(ref l) = app.primary.layer {
            l.draw(g, app);
        }

        if let Some(ref c) = self.controls.common {
            c.draw(g, app);
        } else {
            CommonState::draw_osd(g, app);
        }
        if let Some(ref tp) = self.controls.tool_panel {
            tp.draw(g);
        }
        if let Some(ref s) = self.controls.speed {
            s.draw(g);
        }
        if let Some(ref tp) = self.controls.time_panel {
            tp.draw(g);
        }
        if let Some(ref am) = self.controls.agent_meter {
            am.draw(g);
        }
        if let Some(ref m) = self.controls.minimap {
            m.draw(g, app);
        }
        if let Some(ref r) = self.controls.route_preview {
            r.draw(g);
        }

        self.gameplay.draw(g, app);
    }

    fn on_destroy(&mut self, _: &mut EventCtx, app: &mut App) {
        app.primary.layer = None;
        app.primary.agents.borrow_mut().unzoomed_agents = UnzoomedAgents::new(&app.cs);
        self.gameplay.on_destroy(app);
    }
}

pub fn maybe_exit_sandbox(ctx: &mut EventCtx) -> Transition {
    Transition::Push(ChooseSomething::new(
        ctx,
        "Are you ready to leave this mode?",
        vec![
            Choice::string("keep playing"),
            Choice::string("quit to main screen").key(Key::Q),
        ],
        Box::new(|resp, ctx, app| {
            if resp == "keep playing" {
                return Transition::Pop;
            }

            if app.primary.map.unsaved_edits() {
                return Transition::Multi(vec![
                    Transition::Push(Box::new(BackToMainMenu)),
                    Transition::Push(SaveEdits::new(
                        ctx,
                        app,
                        "Do you want to save your proposal first?",
                        true,
                        None,
                        Box::new(|_, _| {}),
                    )),
                ]);
            }
            Transition::Replace(Box::new(BackToMainMenu))
        }),
    ))
}

struct BackToMainMenu;

impl State<App> for BackToMainMenu {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        app.clear_everything(ctx);
        Transition::Clear(vec![MainMenu::new(ctx)])
    }

    fn draw(&self, _: &mut GfxCtx, _: &App) {}
}

pub struct AgentMeter {
    time: Time,
    pub panel: Panel,
}

impl AgentMeter {
    pub fn new(ctx: &mut EventCtx, app: &App) -> AgentMeter {
        let mut row = Vec::new();
        let (finished, unfinished) = app.primary.sim.num_trips();
        let counts = app.primary.sim.num_commuters_vehicles();

        row.push(Widget::custom_row(vec![
            Image::icon("system/assets/meters/pedestrian.svg")
                .tooltip(Text::from_multiline(vec![
                    Line("Pedestrians"),
                    Line(format!(
                        "Walking commuters: {}",
                        prettyprint_usize(counts.walking_commuters)
                    ))
                    .secondary(),
                    Line(format!(
                        "To/from public transit: {}",
                        prettyprint_usize(counts.walking_to_from_transit)
                    ))
                    .secondary(),
                    Line(format!(
                        "To/from a car: {}",
                        prettyprint_usize(counts.walking_to_from_car)
                    ))
                    .secondary(),
                    Line(format!(
                        "To/from a bike: {}",
                        prettyprint_usize(counts.walking_to_from_bike)
                    ))
                    .secondary(),
                ]))
                .into_widget(ctx)
                .margin_right(5),
            prettyprint_usize(
                counts.walking_commuters
                    + counts.walking_to_from_transit
                    + counts.walking_to_from_car
                    + counts.walking_to_from_bike,
            )
            .draw_text(ctx),
        ]));

        row.push(Widget::custom_row(vec![
            Image::icon("system/assets/meters/bike.svg")
                .tooltip(Text::from_multiline(vec![
                    Line("Cyclists"),
                    Line(prettyprint_usize(counts.cyclists)).secondary(),
                ]))
                .into_widget(ctx)
                .margin_right(5),
            prettyprint_usize(counts.cyclists).draw_text(ctx),
        ]));

        row.push(Widget::custom_row(vec![
            Image::icon("system/assets/meters/car.svg")
                .tooltip(Text::from_multiline(vec![
                    Line("Cars"),
                    Line(format!(
                        "Single-occupancy vehicles: {}",
                        prettyprint_usize(counts.sov_drivers)
                    ))
                    .secondary(),
                ]))
                .into_widget(ctx)
                .margin_right(5),
            prettyprint_usize(counts.sov_drivers).draw_text(ctx),
        ]));

        row.push(Widget::custom_row(vec![
            Image::icon("system/assets/meters/bus.svg")
                .tooltip(Text::from_multiline(vec![
                    Line("Public transit"),
                    Line(format!(
                        "{} passengers on {} buses",
                        prettyprint_usize(counts.bus_riders),
                        prettyprint_usize(counts.buses)
                    ))
                    .secondary(),
                    Line(format!(
                        "{} passengers on {} trains",
                        prettyprint_usize(counts.train_riders),
                        prettyprint_usize(counts.trains)
                    ))
                    .secondary(),
                ]))
                .into_widget(ctx)
                .margin_right(5),
            prettyprint_usize(counts.bus_riders + counts.train_riders).draw_text(ctx),
        ]));

        let mut rows = vec![
            "Active trips".draw_text(ctx),
            Widget::custom_row(row).centered(),
            Widget::horiz_separator(ctx, 0.2),
            Widget::row(vec![
                {
                    let mut txt = Text::new();
                    let pct = if unfinished == 0 {
                        100.0
                    } else {
                        100.0 * (finished as f64) / ((finished + unfinished) as f64)
                    };
                    txt.add(Line(format!(
                        "Finished trips: {} ({}%)",
                        prettyprint_usize(finished),
                        pct as usize
                    )));
                    txt.draw(ctx).centered_vert()
                },
                if app.primary.dirty_from_edits {
                    ctx.style()
                        .btn_plain_icon("system/assets/tools/warning.svg")
                        .build_widget(ctx, "see why results are tentative")
                        .centered_vert()
                        .align_right()
                } else {
                    Widget::nothing()
                },
                ctx.style()
                    .btn_plain_icon("system/assets/meters/trip_histogram.svg")
                    .hotkey(Key::Q)
                    .build_widget(ctx, "more data")
                    .align_right(),
            ]),
        ];
        // TODO This likely fits better in the top center panel, but no easy way to squeeze it into
        // the panel for all gameplay modes
        if let Some(n) = app.primary.sim.num_recorded_trips() {
            rows.push(Widget::row(vec![
                Widget::draw_batch(
                    ctx,
                    GeomBatch::from(vec![(
                        Color::RED,
                        Circle::new(Pt2D::new(0.0, 0.0), Distance::meters(10.0)).to_polygon(),
                    )]),
                )
                .centered_vert(),
                format!("{} trips captured", prettyprint_usize(n)).draw_text(ctx),
                ctx.style()
                    .btn_solid_text("Stop")
                    .build_def(ctx)
                    .align_right(),
            ]));
        }

        let panel = Panel::new(Widget::col(rows))
            .aligned(HorizontalAlignment::Right, VerticalAlignment::Top)
            .build(ctx);

        AgentMeter {
            time: app.primary.sim.time(),
            panel,
        }
    }

    pub fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Option<Transition> {
        if self.time != app.primary.sim.time() {
            *self = AgentMeter::new(ctx, app);
            return self.event(ctx, app);
        }
        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "more data" => {
                    return Some(Transition::Push(dashboards::FinishedTripTable::new(
                        ctx, app,
                    )));
                }
                "see why results are tentative" => {
                    return Some(Transition::Push(PopupMsg::new(
                        ctx,
                        "Simulation results not finalized",
                        vec![
                            "You edited the map in the middle of the day.",
                            "Some trips may have been interrupted, and others might have made \
                             different decisions if they saw the new map from the start.",
                            "To get final results, reset to midnight and test your proposal over \
                             a full day.",
                        ],
                    )));
                }
                "Stop" => {
                    app.primary.sim.save_recorded_traffic(&app.primary.map);
                }
                _ => unreachable!(),
            },
            _ => {}
        }

        None
    }

    pub fn draw(&self, g: &mut GfxCtx) {
        self.panel.draw(g);
    }
}

// pub for Warping
pub struct Actions {
    is_paused: bool,
    can_interact: bool,
    gameplay: GameplayMode,
}
impl ContextualActions for Actions {
    fn actions(&self, app: &App, id: ID) -> Vec<(Key, String)> {
        let mut actions = Vec::new();
        if self.can_interact {
            match id.clone() {
                ID::Intersection(i) => {
                    if app.primary.map.get_i(i).is_traffic_signal() {
                        actions.push((Key::E, "edit traffic signal".to_string()));
                    }
                    if app.primary.map.get_i(i).is_stop_sign()
                        && self.gameplay.can_edit_stop_signs()
                    {
                        actions.push((Key::E, "edit stop sign".to_string()));
                    }
                    if app.opts.dev {
                        actions.push((Key::U, "explore uber-turns".to_string()));
                        if app.primary.sim.num_recorded_trips().is_none() {
                            actions.push((Key::R, "record traffic here".to_string()));
                        }
                    }
                }
                ID::Lane(l) => {
                    if !app.primary.map.get_turns_from_lane(l).is_empty() {
                        actions.push((Key::Z, "explore turns from this lane".to_string()));
                    }
                    if can_edit_lane(&self.gameplay, l, app) {
                        actions.push((Key::E, "edit lane".to_string()));
                    }
                }
                ID::Building(b) => {
                    if Favorites::contains(app, b) {
                        actions.push((Key::F, "remove this building from favorites".to_string()));
                    } else {
                        actions.push((Key::F, "add this building to favorites".to_string()));
                    }
                }
                _ => {}
            }
        }
        actions.extend(match self.gameplay {
            GameplayMode::Freeform(_) => gameplay::freeform::actions(app, id),
            GameplayMode::Tutorial(_) => gameplay::tutorial::actions(app, id),
            _ => Vec::new(),
        });
        actions
    }
    fn execute(
        &mut self,
        ctx: &mut EventCtx,
        app: &mut App,
        id: ID,
        action: String,
        close_panel: &mut bool,
    ) -> Transition {
        match (id, action.as_ref()) {
            (ID::Intersection(i), "edit traffic signal") => Transition::Multi(vec![
                Transition::Push(EditMode::new(ctx, app, self.gameplay.clone())),
                Transition::Push(TrafficSignalEditor::new(
                    ctx,
                    app,
                    btreeset! {i},
                    self.gameplay.clone(),
                )),
            ]),
            (ID::Intersection(i), "edit stop sign") => Transition::Multi(vec![
                Transition::Push(EditMode::new(ctx, app, self.gameplay.clone())),
                Transition::Push(StopSignEditor::new(ctx, app, i, self.gameplay.clone())),
            ]),
            (ID::Intersection(i), "explore uber-turns") => {
                Transition::Push(uber_turns::UberTurnPicker::new(ctx, app, i))
            }
            (ID::Intersection(i), "record traffic here") => {
                Transition::Push(TrafficRecorder::new(ctx, btreeset! {i}))
            }
            (ID::Lane(l), "explore turns from this lane") => {
                Transition::Push(TurnExplorer::new(ctx, app, l))
            }
            (ID::Lane(l), "edit lane") => Transition::Multi(vec![
                Transition::Push(EditMode::new(ctx, app, self.gameplay.clone())),
                Transition::Push(LaneEditor::new(ctx, app, l, self.gameplay.clone())),
            ]),
            (ID::Building(b), "add this building to favorites") => {
                Favorites::add(app, b);
                app.primary.layer = Some(Box::new(ShowFavorites::new(ctx, app)));
                Transition::Keep
            }
            (ID::Building(b), "remove this building from favorites") => {
                Favorites::remove(app, b);
                app.primary.layer = Some(Box::new(ShowFavorites::new(ctx, app)));
                Transition::Keep
            }
            (_, "follow (run the simulation)") => {
                *close_panel = false;
                Transition::ModifyState(Box::new(|state, ctx, app| {
                    let mode = state.downcast_mut::<SandboxMode>().unwrap();
                    let speed = mode.controls.speed.as_mut().unwrap();
                    assert!(speed.is_paused());
                    speed.resume_realtime(ctx, app);
                }))
            }
            (_, "unfollow (pause the simulation)") => {
                *close_panel = false;
                Transition::ModifyState(Box::new(|state, ctx, app| {
                    let mode = state.downcast_mut::<SandboxMode>().unwrap();
                    let speed = mode.controls.speed.as_mut().unwrap();
                    assert!(!speed.is_paused());
                    speed.pause(ctx, app);
                }))
            }
            (id, action) => match self.gameplay {
                GameplayMode::Freeform(_) => gameplay::freeform::execute(ctx, app, id, action),
                GameplayMode::Tutorial(_) => gameplay::tutorial::execute(ctx, app, id, action),
                _ => unreachable!(),
            },
        }
    }
    fn is_paused(&self) -> bool {
        self.is_paused
    }
    fn gameplay_mode(&self) -> GameplayMode {
        self.gameplay.clone()
    }
}

// TODO Setting SandboxMode up is quite convoluted, all in order to support asynchronously loading
// files on the web. Each LoadStage is followed in order, with some optional short-circuiting.
//
// Ideally there'd be a much simpler way to express this using Rust's async, to let the compiler
// express this state machine for us.

enum LoadStage {
    LoadingMap,
    LoadingScenario,
    GotScenario(Scenario),
    // Scenario name
    LoadingPrebaked(String),
    // Scenario name, maybe prebaked data
    GotPrebaked(String, Result<Analytics>),
    Finalizing,
}

struct SandboxLoader {
    // Always exists, just a way to avoid clones
    stage: Option<LoadStage>,
    mode: GameplayMode,
    finalize: Option<Box<dyn FnOnce(&mut EventCtx, &mut App) -> Vec<Transition>>>,
}

impl State<App> for SandboxLoader {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        loop {
            match self.stage.take().unwrap() {
                LoadStage::LoadingMap => {
                    return Transition::Push(MapLoader::new(
                        ctx,
                        app,
                        self.mode.map_name().clone(),
                        Box::new(|_, _| {
                            Transition::Multi(vec![
                                Transition::Pop,
                                Transition::ModifyState(Box::new(|state, _, _| {
                                    let loader = state.downcast_mut::<SandboxLoader>().unwrap();
                                    loader.stage = Some(LoadStage::LoadingScenario);
                                })),
                            ])
                        }),
                    ));
                }
                LoadStage::LoadingScenario => {
                    // TODO Can we cache the dynamically generated scenarios, like home_to_work, and
                    // avoid regenerating with this call?
                    match ctx.loading_screen("load scenario", |_, mut timer| {
                        self.mode.scenario(
                            app,
                            app.primary.current_flags.sim_flags.make_rng(),
                            &mut timer,
                        )
                    }) {
                        gameplay::LoadScenario::Nothing => {
                            app.set_prebaked(None);
                            self.stage = Some(LoadStage::Finalizing);
                            continue;
                        }
                        gameplay::LoadScenario::Scenario(scenario) => {
                            self.stage = Some(LoadStage::GotScenario(scenario));
                            continue;
                        }
                        gameplay::LoadScenario::Future(future) => {
                            use map_gui::load::FutureLoader;
                            return Transition::Push(FutureLoader::<App, Scenario>::new(
                                ctx,
                                Box::pin(future),
                                "Loading Scenario",
                                Box::new(|_, _, scenario| {
                                    // TODO show error/retry alert?
                                    let scenario =
                                        scenario.expect("failed to load scenario from future");
                                    Transition::Multi(vec![
                                        Transition::Pop,
                                        Transition::ModifyState(Box::new(|state, _, app| {
                                            let loader =
                                                state.downcast_mut::<SandboxLoader>().unwrap();
                                            app.primary.scenario = Some(scenario.clone());
                                            loader.stage = Some(LoadStage::GotScenario(scenario));
                                        })),
                                    ])
                                }),
                            ));
                        }
                        gameplay::LoadScenario::Path(path) => {
                            // Reuse the cached scenario, if possible.
                            if let Some(ref scenario) = app.primary.scenario {
                                if scenario.scenario_name == abstutil::basename(&path) {
                                    self.stage = Some(LoadStage::GotScenario(scenario.clone()));
                                    continue;
                                }
                            }

                            return Transition::Push(FileLoader::<App, Scenario>::new(
                                ctx,
                                path,
                                Box::new(|_, _, _, scenario| {
                                    // TODO Handle corrupt files
                                    let scenario = scenario.unwrap();
                                    Transition::Multi(vec![
                                        Transition::Pop,
                                        Transition::ModifyState(Box::new(|state, _, app| {
                                            let loader =
                                                state.downcast_mut::<SandboxLoader>().unwrap();
                                            app.primary.scenario = Some(scenario.clone());
                                            loader.stage = Some(LoadStage::GotScenario(scenario));
                                        })),
                                    ])
                                }),
                            ));
                        }
                    }
                }
                LoadStage::GotScenario(mut scenario) => {
                    let scenario_name = scenario.scenario_name.clone();
                    ctx.loading_screen("instantiate scenario", |_, mut timer| {
                        if let GameplayMode::PlayScenario(_, _, ref modifiers) = self.mode {
                            for m in modifiers {
                                scenario = m.apply(&app.primary.map, scenario);
                            }
                        }

                        scenario.instantiate(
                            &mut app.primary.sim,
                            &app.primary.map,
                            &mut app.primary.current_flags.sim_flags.make_rng(),
                            &mut timer,
                        );
                        app.primary
                            .sim
                            .tiny_step(&app.primary.map, &mut app.primary.sim_cb);
                    });

                    self.stage = Some(LoadStage::LoadingPrebaked(scenario_name));
                    continue;
                }
                LoadStage::LoadingPrebaked(scenario_name) => {
                    // Maybe we've already got prebaked data for this map+scenario.
                    if app
                        .has_prebaked()
                        .map(|(m, s)| m == app.primary.map.get_name() && s == &scenario_name)
                        .unwrap_or(false)
                    {
                        self.stage = Some(LoadStage::Finalizing);
                        continue;
                    }

                    return Transition::Push(FileLoader::<App, Analytics>::new(
                        ctx,
                        abstio::path_prebaked_results(app.primary.map.get_name(), &scenario_name),
                        Box::new(move |_, _, _, prebaked| {
                            Transition::Multi(vec![
                                Transition::Pop,
                                Transition::ModifyState(Box::new(move |state, _, _| {
                                    let loader = state.downcast_mut::<SandboxLoader>().unwrap();
                                    loader.stage =
                                        Some(LoadStage::GotPrebaked(scenario_name, prebaked));
                                })),
                            ])
                        }),
                    ));
                }
                LoadStage::GotPrebaked(scenario_name, prebaked) => {
                    match prebaked {
                        Ok(prebaked) => {
                            app.set_prebaked(Some((
                                app.primary.map.get_name().clone(),
                                scenario_name,
                                prebaked,
                            )));
                        }
                        Err(err) => {
                            warn!(
                                "No prebaked simulation results for \"{}\" scenario on {} map. \
                                 This means trip dashboards can't compare current times to any \
                                 kind of baseline: {}",
                                scenario_name,
                                app.primary.map.get_name().describe(),
                                err
                            );
                            app.set_prebaked(None);
                        }
                    }
                    self.stage = Some(LoadStage::Finalizing);
                    continue;
                }
                LoadStage::Finalizing => {
                    let mut gameplay = self.mode.initialize(ctx, app);
                    gameplay.recreate_panels(ctx, app);
                    let sandbox = Box::new(SandboxMode {
                        controls: SandboxControls::new(ctx, app, &gameplay),
                        gameplay,
                        gameplay_mode: self.mode.clone(),
                        recalc_unzoomed_agent: None,
                        last_cs: app.opts.color_scheme,
                    });

                    let mut transitions = vec![Transition::Replace(sandbox)];
                    transitions.extend((self.finalize.take().unwrap())(ctx, app));
                    return Transition::Multi(transitions);
                }
            }
        }
    }

    fn draw(&self, _: &mut GfxCtx, _: &App) {}
}

fn mouseover_unzoomed_agent_circle(ctx: &mut EventCtx, app: &mut App) {
    let cursor = if let Some(pt) = ctx.canvas.get_cursor_in_map_space() {
        pt
    } else {
        return;
    };

    for (id, _, _) in app
        .primary
        .agents
        .borrow_mut()
        .calculate_unzoomed_agents(ctx, app)
        .query(
            Circle::new(cursor, Distance::meters(3.0))
                .get_bounds()
                .as_bbox(),
        )
    {
        if let Some(pt) = app
            .primary
            .sim
            .canonical_pt_for_agent(*id, &app.primary.map)
        {
            if Circle::new(pt, unzoomed_agent_radius(id.to_vehicle_type())).contains_pt(cursor) {
                app.primary.current_selection = Some(ID::from_agent(*id));
            }
        }
    }
}

fn is_daytime(app: &App) -> bool {
    let hours = app.primary.sim.time().get_parts().0 % 24;
    hours >= 6 && hours < 18
}

impl SandboxControls {
    pub fn new(
        ctx: &mut EventCtx,
        app: &App,
        gameplay: &Box<dyn gameplay::GameplayState>,
    ) -> SandboxControls {
        SandboxControls {
            common: if gameplay.has_common() {
                Some(CommonState::new())
            } else {
                None
            },
            route_preview: if gameplay.can_examine_objects() {
                Some(RoutePreview::new())
            } else {
                None
            },
            tool_panel: if gameplay.has_tool_panel() {
                Some(tool_panel(ctx))
            } else {
                None
            },
            time_panel: if gameplay.has_time_panel() {
                Some(TimePanel::new(ctx, app))
            } else {
                None
            },
            speed: if gameplay.has_speed() {
                Some(SpeedControls::new(ctx, app))
            } else {
                None
            },
            agent_meter: if gameplay.has_agent_meter() {
                Some(AgentMeter::new(ctx, app))
            } else {
                None
            },
            minimap: if gameplay.has_minimap() {
                Some(Minimap::new(ctx, app, MinimapController))
            } else {
                None
            },
        }
    }

    fn recreate_panels(&mut self, ctx: &mut EventCtx, app: &App) {
        if self.tool_panel.is_some() {
            self.tool_panel = Some(tool_panel(ctx));
        }
        if let Some(ref mut speed) = self.speed {
            speed.recreate_panel(ctx, app);
        }
        if let Some(ref mut minimap) = self.minimap {
            minimap.recreate_panel(ctx, app);
        }
    }
}

/// Calculates an OSM-style `zoom/lat/lon` string
/// (https://wiki.openstreetmap.org/wiki/Browsing#Other_URL_tricks) based on the current viewport.
// TODO Lift to map_gui along with parse_center_camera.
fn calculate_camera_center(ctx: &EventCtx, app: &App) -> String {
    let center = ctx
        .canvas
        .center_to_map_pt()
        .to_gps(app.primary.map.get_gps_bounds());

    // To calculate zoom, just solve for the inverse of the code in parse_center_camera.
    let earth_circumference_equator = 40_075_016.686;
    let log_arg = earth_circumference_equator * center.y().to_radians().cos() * ctx.canvas.cam_zoom;
    let zoom_lvl = log_arg.log2() - 8.0;

    // Trim precision
    format!("{:.2}/{:.5}/{:.5}", zoom_lvl, center.y(), center.x())
}