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
#[macro_use]
extern crate log;

use abstutil::{CmdArgs, Timer};
use geom::Duration;
use sim::{ScenarioModifier, SimFlags};

use crate::app::Flags;

mod app;
mod challenges;
mod colors;
mod common;
mod cutscene;
mod debug;
mod devtools;
mod edit;
mod game;
mod helpers;
mod info;
mod layer;
mod load;
mod options;
mod pregame;
mod render;
mod sandbox;

pub fn main() {
    let mut args = CmdArgs::new();

    if args.enabled("--prebake") {
        challenges::prebake_all();
        return;
    }
    if args.enabled("--smoketest") {
        smoke_test();
        return;
    }
    if args.enabled("--check_proposals") {
        check_proposals();
        return;
    }

    let mut flags = Flags {
        sim_flags: SimFlags::from_args(&mut args),
        num_agents: args.optional_parse("--num_agents", |s| s.parse()),
        live_map_edits: args.enabled("--live_map_edits"),
    };
    let mut opts = options::Options::default();
    opts.dev = args.enabled("--dev");
    if args.enabled("--lowzoom") {
        opts.min_zoom_for_detail = 1.0;
    }

    if let Some(x) = args.optional("--color_scheme") {
        let mut ok = false;
        let mut options = Vec::new();
        for c in colors::ColorSchemeChoice::choices() {
            options.push(c.label.clone());
            if c.label == x {
                opts.color_scheme = c.data;
                ok = true;
                break;
            }
        }
        if !ok {
            panic!(
                "Invalid --color_scheme={}. Choices: {}",
                x,
                options.join(", ")
            );
        }
    }
    let mut settings = widgetry::Settings::new("A/B Street");
    settings.window_icon(abstutil::path("system/assets/pregame/icon.png"));
    if args.enabled("--enable_profiler") {
        settings.enable_profiling();
    }
    if args.enabled("--dump_raw_events") {
        settings.dump_raw_events();
    }
    if let Some(s) = args.optional_parse("--scale_factor", |s| s.parse::<f64>()) {
        settings.scale_factor(s);
    }
    settings.loading_tips(helpers::loading_tips());

    let mut mode = None;
    if let Some(x) = args.optional("--challenge") {
        let mut aliases = Vec::new();
        'OUTER: for (_, stages) in challenges::Challenge::all() {
            for challenge in stages {
                if challenge.alias == x {
                    flags.sim_flags.load = abstutil::path_map(challenge.gameplay.map_name());
                    mode = Some(challenge.gameplay);
                    break 'OUTER;
                } else {
                    aliases.push(challenge.alias);
                }
            }
        }
        if mode.is_none() {
            panic!("Invalid --challenge={}. Choices: {}", x, aliases.join(", "));
        }
    }
    if let Some(n) = args.optional_parse("--tutorial", |s| s.parse::<usize>()) {
        mode = Some(sandbox::GameplayMode::Tutorial(
            sandbox::TutorialPointer::new(n - 1, 0),
        ));
    }
    if mode.is_none() && flags.sim_flags.load.contains("scenarios/") {
        // TODO regex
        let parts = flags.sim_flags.load.split("/").collect::<Vec<_>>();
        let map_name = parts[parts.len() - 2].to_string();
        let scenario = abstutil::basename(parts[parts.len() - 1]);
        flags.sim_flags.load = abstutil::path_map(&map_name);

        let modifiers: Vec<ScenarioModifier> = args
            .optional_parse("--scenario_modifiers", |s| {
                abstutil::from_json(&s.to_string().into_bytes())
            })
            .unwrap_or_else(Vec::new);

        mode = Some(sandbox::GameplayMode::PlayScenario(
            map_name, scenario, modifiers,
        ));
    }
    let start_with_edits = args.optional("--edits");

    args.done();

    widgetry::run(settings, |ctx| {
        let g = game::Game::new(flags, opts, start_with_edits, mode, ctx);
        g
    });
}

fn smoke_test() {
    let mut timer = Timer::new("run a smoke-test for all maps");
    for name in abstutil::list_all_objects(abstutil::path_all_maps()) {
        let map = map_model::Map::new(abstutil::path_map(&name), &mut timer);
        let scenario = if map.get_city_name() == "seattle" {
            abstutil::read_binary(abstutil::path_scenario(&name, "weekday"), &mut timer)
        } else {
            let mut rng = sim::SimFlags::for_test("smoke_test").make_rng();
            sim::ScenarioGenerator::proletariat_robot(&map, &mut rng, &mut timer)
        };

        let mut opts = sim::SimOptions::new("smoke_test");
        opts.alerts = sim::AlertHandler::Silence;
        let mut sim = sim::Sim::new(&map, opts, &mut timer);
        // Bit of an abuse of this, but just need to fix the rng seed.
        let mut rng = sim::SimFlags::for_test("smoke_test").make_rng();
        scenario.instantiate(&mut sim, &map, &mut rng, &mut timer);
        sim.timed_step(&map, Duration::hours(1), &mut None, &mut timer);

        if vec![
            "downtown",
            "krakow_center",
            "lakeslice",
            "montlake",
            "udistrict",
        ]
        .contains(&name.as_str())
        {
            dump_route_goldenfile(&map).unwrap();
        }
    }
}

fn dump_route_goldenfile(map: &map_model::Map) -> Result<(), std::io::Error> {
    use std::fs::File;
    use std::io::Write;

    let path = abstutil::path(format!("route_goldenfiles/{}.txt", map.get_name()));
    let mut f = File::create(path)?;
    for br in map.all_bus_routes() {
        writeln!(
            f,
            "{} from {} to {:?}",
            br.osm_rel_id, br.start, br.end_border
        )?;
        for bs in &br.stops {
            let bs = map.get_bs(*bs);
            writeln!(
                f,
                "  {}: {} driving, {} sidewalk",
                bs.name, bs.driving_pos, bs.sidewalk_pos
            )?;
        }
    }
    Ok(())
}

fn check_proposals() {
    let mut timer = Timer::new("check all proposals");
    for name in abstutil::list_all_objects(abstutil::path("system/proposals")) {
        match abstutil::maybe_read_json::<map_model::PermanentMapEdits>(
            abstutil::path(format!("system/proposals/{}.json", name)),
            &mut timer,
        ) {
            Ok(perma) => {
                let map = map_model::Map::new(abstutil::path_map(&perma.map_name), &mut timer);
                if let Err(err) = map_model::PermanentMapEdits::from_permanent(perma, &map) {
                    timer.error(format!("{} is out-of-date: {}", name, err));
                }
            }
            Err(err) => {
                timer.error(format!("{} JSON is broken: {}", name, err));
            }
        }
    }
}

#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen(start)]
pub fn run() {
    console_log::init_with_level(log::Level::Debug).unwrap();

    main();
}