nano9 0.1.0-alpha.7

A Pico-8 compatibility layer for Bevy
Documentation
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
use bevy::{
    asset::{
        AssetPath,
        io::{AssetSourceBuilder, AssetSourceId},
    },
    prelude::*,
};
use clap::{Parser, Subcommand};
use nano9::{
    config::{load_and_insert_pico8, pause_pico8_when_loaded, run_pico8_when_loaded},
    pico8::{CartLoaderSettings, Pico8Asset, Pico8Handle, SharedData},
    *,
};
use std::{env, ffi::OsStr, fs, io, path::PathBuf, process::ExitCode};

#[derive(Parser)]
#[command(version, about, long_about, disable_help_subcommand = true,
          // subcommand_required = true,
          // arg_required_else_help = true,
)]
// #[command(next_line_help = true)]
struct Cli {
    // /// Optional name to operate on
    // name: Option<String>,

    // Sets a custom config file
    // #[arg(short, long, value_name = "FILE")]
    // config: Option<PathBuf>,

    // /// Turn debugging information on
    // #[arg(short, long, action = clap::ArgAction::Count)]
    // debug: u8,
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Run a Pico-8 cart or Nano-9 project
    ///
    /// Environment variables:
    ///
    /// NANO9_ASSETS   - override the assets directory
    /// 
    /// NANO9_LUA_CODE - log the translated code to file
    Run {
        /// Run path.
        path: PathBuf,

        #[arg(long)]
        /// Start paused.
        pause: bool,
        #[arg(long)]
        /// Shared data for Pico-8 carts
        shared_data: Option<SharedData>,
    },
    /// Check a Pico-8 cart or Nano-9 project
    ///
    /// Environment variables:
    ///
    /// NANO9_ASSETS - override the assets directory
    /// NANO9_LUA_CODE   - log the translated code to file
    Check {
        /// Run path.
        path: PathBuf,
    },
    /// Create a new Nano-9 project
    ///
    /// Depending on the extension and arguments, it will create the following kind of project:
    ///   - FILE.p8lua, a one file Pico-8 Lua game with embedded config
    ///   - FILE.lua, a one file Lua game with embedded config
    ///   - [--language lua] FILE, a directory with config and Lua scripts (no Rust)
    ///   - --language rust FILE, a Rust-only crate with config in assets directory
    ///   - --language lua-rust FILE, a Rust crate with config and Lua scripts in assets directory
    #[command(verbatim_doc_comment)]
    New {
        /// Language
        // #[arg(long, default_value = "lua")]
        #[arg(long)]
        language: Option<Language>,
        /// Choose a starter template
        #[arg(long)]
        starter: Option<StarterKit>,
        /// Overwrite files if present
        #[arg(long)]
        force: bool,
        /// Destination path
        ///
        /// A one-file project is created if the path ends with the following
        /// extensions: .p8lua and .lua.
        path: PathBuf,
    },
    /// Report on available features
    Info {},
}

#[derive(Debug, Clone, clap::ValueEnum, PartialEq)]
enum Language {
    Rust,
    Lua,
    LuaRust,
}

#[derive(Debug, Clone, clap::ValueEnum)]
enum StarterKit {
    Platformer,
    TopDown,
}

const HELLO_WORLD: &str = include_str!("templates/main.lua");
// Secondary command line interface used as fallback.
//
// [source](https://stackoverflow.com/a/79564853/6454690)
#[derive(Parser)]
#[command(long_about = None)]
struct CliDefault {
    #[arg(long)]
    shared_data: Option<SharedData>,
    #[arg(long)]
    pause: bool,
    path: PathBuf,
}

fn main() -> io::Result<ExitCode> {
    let cli = match Cli::try_parse().or_else(|err| match err.kind() {
        clap::error::ErrorKind::InvalidSubcommand => CliDefault::try_parse()
            .map(|cli_default| Cli {
                command: Command::Run {
                    path: cli_default.path,
                    shared_data: cli_default.shared_data,
                    pause: cli_default.pause,
                },
            })
            .map_err(|_| err),
        _ => Err(err),
    }) {
        Ok(cli) => cli,
        Err(err) => {
            err.print().expect("error writing usage");
            // this will print any errors the same way as Cli::parse() would
            return Ok(ExitCode::from(err.exit_code() as u8));
        }
    };
    // let cli = Cli::parse();
    // let example_files = [
    //     "cart.p8",
    //     "cart.p8.png",
    //     "code.lua", // Lua
    //     // "code.pua", // Pico-8 dialect
    //     "game-dir",
    //     "game-dir/Nano9.toml",
    //     "code.n9",
    // ];
    match cli.command {
        Command::Run { .. } | Command::Check { .. } => run(cli),
        Command::New { .. } => new(cli),
        Command::Info { .. } => info(cli),
    }
}

fn info(_cli: Cli) -> io::Result<ExitCode> {
    macro_rules! feature_info {
        ($feature:literal, $description:literal, $enabled_by_default:expr) => {{
            let mark: char = match (cfg!(feature = $feature), $enabled_by_default) {
                (true, true) => 'x',
                (false, true) => '_',
                (true, false) => 'X',
                (false, false) => ' ',
            };
            println!("  - [{}] {:?} {}", mark, $feature, $description);
        }};
    }
    println!(
        r#"The following features are available. Use this key:
                                    - [x] enabled and enabled by default
                                    - [X] enabled and disabled by default
                                    - [_] disabled and enabled by default
                                    - [ ] disabled and disabled by default"#
    );
    feature_info!("scripting", "for Lua scripting", true);
    feature_info!("negate-y", "uses Pico-8's positive-y is downward", true);
    feature_info!("pixel-snap", "applies floor to pixel locations", true);
    feature_info!("pico8-to-lua", "converts Pico-8's dialect to Lua", true);
    feature_info!(
        "fixed-point",
        "uses fixed-point numbers for bit operations",
        true
    );
    feature_info!("web-asset", "allows URLs for asset locations", false);
    feature_info!("minibuffer", "embeds a gamedev console", false);
    feature_info!("inspector", "adds inspector commands to console", false);
    feature_info!("cli", "command line interface for n9", true);
    Ok(ExitCode::from(0))
}

fn new(cli: Cli) -> io::Result<ExitCode> {
    match cli.command {
        Command::New {
            language,
            starter,
            path,
            force,
        } => {
            use log::info;
            env_logger::Builder::from_env(
                env_logger::Env::default().default_filter_or("info,n9=info"),
            )
            .format_timestamp(None)
            .init();
            if let Some(extension) = path.extension().and_then(|s| s.to_str()) {
                match extension {
                    "lua" | "p8lua" => {
                        // Copy the p8lua template.
                        let content = include_str!("../../assets/pset.lua");
                        fs::write(path, content)?;
                        Ok(ExitCode::from(0))
                    }
                    ext => {
                        eprintln!("error: No template for extension {ext:?}.");
                        Ok(ExitCode::from(5))
                    }
                }
            } else {
                // It's a directory path.
                let assets_path = match language {
                    lang @ Some(Language::Rust | Language::LuaRust) => {
                        use cmd_lib::run_cmd;
                        info!("Creating new cargo project at {:?}.", &path);
                        let lang = lang.unwrap();
                        let feature = match lang {
                            Language::Rust => "rust-lib",
                            Language::LuaRust => "lua-lib",
                            Language::Lua => unreachable!(),
                        };
                        match run_cmd!(
                            cargo new $path;
                            cd $path;
                            cargo add bevy@0.15;
                            cargo add nano9 --git "https://github.com/shanecelis/nano9.git" --branch dev --no-default-features --features $feature;
                        ) {
                            Ok(_) => {
                                // Copy files
                                let content = include_str!("templates/Nano9.toml");
                                let mut p = path.to_path_buf();
                                p.push("assets");
                                fs::create_dir_all(&p)?;
                                p.push("Nano9.toml");
                                info!("Creating Nano-9 config at {:?}.", &p);
                                fs::write(&p, content)?;

                                if lang == Language::LuaRust {
                                    let _ = p.pop();
                                    p.push("main.lua");
                                    info!("Creating main Lua code at {:?}.", &p);
                                    fs::write(&p, HELLO_WORLD)?;

                                    let content = include_str!("templates/main-lua-rust.rs.txt");
                                    let _ = p.pop();
                                    let _ = p.pop();
                                    p.push("src/main.rs");
                                    info!("Creating main Rust code at {:?}.", &p);
                                    fs::write(&p, content)?;
                                } else {
                                    let content = include_str!("templates/main-rust.rs.txt");
                                    let _ = p.pop();
                                    let _ = p.pop();
                                    p.push("src/main.rs");
                                    info!("Creating main Rust code at {:?}.", &p);
                                    fs::write(&p, content)?;
                                }
                            }
                            Err(e) => {
                                error!("error: Problem running cargo {e}");
                                return Ok(ExitCode::from(8));
                            }
                        }
                        let mut p = path.to_path_buf();
                        p.push("assets");
                        Some(p)
                    }
                    Some(Language::Lua) | None => {
                        if path.exists() {
                            if path.is_file() {
                                error!("error: {path:?} is a file; a directory was expected.");
                                return Ok(ExitCode::from(6));
                            }
                            if path.is_dir() && !force {
                                error!(
                                    "error: {path:?} already exists, canceling; cautiously use --force to overwrite."
                                );
                                return Ok(ExitCode::from(7));
                            }
                        } else {
                            fs::create_dir_all(&path)?;
                        }
                        copy_template!("../../examples/sprite/Nano9.toml", path, "Nano9.toml");

                        copy_template!("../../examples/sprite/main.p8lua", path, "main.lua");
                        // let config = include_str!("../../examples/sprite/Nano9.toml");
                        // let mut p = path.to_path_buf();
                        // p.push("Nano9.toml");
                        // fs::write(&p, config)?;

                        // let code = include_str!("../../examples/sprite/main.p8lua");
                        // let mut code_path = path.to_path_buf();
                        // code_path.push("main.lua");
                        // fs::write(&code_path, code)?;
                        Some(path.to_path_buf())
                    }
                };
                if starter.is_some() && assets_path.is_none() {
                    error!(
                        "No assets path to copy template to for starter kit {:?}",
                        starter
                    );
                    return Ok(ExitCode::from(9));
                }
                match starter {
                    Some(StarterKit::Platformer) => {
                        if let Some(assets_path) = assets_path {
                            copy_template!(
                                "templates/platformer/Nano9.toml",
                                assets_path,
                                "Nano9.toml"
                            );
                            copy_template!(
                                "templates/platformer/actor.p8",
                                assets_path,
                                "actor.p8"
                            );
                            copy_template!(
                                "templates/platformer/dolly.p8",
                                assets_path,
                                "dolly.p8"
                            );
                            copy_template!(
                                "templates/platformer/main.lua",
                                assets_path,
                                "main.lua"
                            );
                            copy_template!(
                                "templates/platformer/micro-platformer.p8",
                                assets_path,
                                "micro-platformer.p8"
                            );
                            copy_template!(
                                "templates/platformer/platformer.p8",
                                assets_path,
                                "platformer.p8"
                            );
                            copy_template!(
                                "templates/platformer/vector.p8",
                                assets_path,
                                "vector.p8"
                            );
                        }
                    }
                    None => (),
                    _ => todo!(),
                }

                Ok(ExitCode::from(0))
            }
        }
        _ => unreachable!(),
    }
}

#[macro_export]
macro_rules! copy_template {
    ($src:expr, $path:expr, $filename:expr) => {{
        let config = include_str!($src);
        let mut p = $path.to_path_buf();
        p.push($filename);
        std::fs::write(&p, config)?;
        let _ = p.pop();
        p
    }};
}

enum Lookup {
    /// There are no defined asset sources.
    Default,
    /// There is one asset source for script and asset lookup.
    One { path: PathBuf },
    /// There are two asset sources, the default one and the script one.
    Two { default: PathBuf, script: PathBuf },
}

fn run(cli: Cli) -> io::Result<ExitCode> {
    let (input_path, shared_data, pause, check) = match cli.command {
        Command::Run {
            path,
            shared_data,
            pause,
        } => (path, shared_data, pause, false),
        Command::Check { path } => (path, None, false, true),
        _ => unreachable!(),
    };

    let invocation_dir = env::current_dir()?;
    let config_path = if input_path.extension() == Some(OsStr::new("toml")) {
        Some(input_path.clone())
    } else if input_path.is_dir() {
        let mut config_path = input_path.clone();
        config_path.push("Nano9.toml");
        Some(config_path)
    } else {
        None
    };
    let script_path = config_path.unwrap_or_else(|| input_path.clone());
    // Choose the default asset root before creating the app so we can register
    // it before AssetPlugin (Default must be registered before AssetPlugin).
    // - If NANO9_ASSETS is set, it always wins.
    // - Otherwise, if the input is a local path, use the "game directory":
    //   - directory arg: that directory
    //   - file arg: parent directory
    //
    // This keeps relative asset paths (scripts, sprite sheets, etc.) resolving the same way for:
    //   (cd examples/sprite && ... check .)
    //   (cd examples && ... check sprite)
    let env_asset_root: Option<PathBuf> = env::var_os("NANO9_ASSETS").map(PathBuf::from);
    let script_asset_root: Option<PathBuf> = if input_path.exists() {
        // Local path
        if input_path.is_dir() {
            Some(input_path)
        } else {
            input_path.parent().map(|p| p.to_path_buf())
        }
    } else {
        None
    };

    let lookup = match (env_asset_root, script_asset_root) {
        (None, None) => Lookup::Default,
        (Some(path), None) => Lookup::One { path },
        (None, Some(path)) => Lookup::One { path },
        (Some(default), Some(script)) => Lookup::Two { default, script },
    };
    let mut app = App::new();
    let mut info_logs = vec![];
    match lookup {
        Lookup::One { ref path }
        | Lookup::Two {
            default: ref path, ..
        } => {
            let mut abs_path = invocation_dir.clone();
            abs_path.push(path);
            info_logs.push(format!(
                "The default assets directory: {:?}",
                abs_path.display()
            ));
            app.register_asset_source(
                &AssetSourceId::Default,
                AssetSourceBuilder::platform_default(
                    abs_path.to_str().expect("default asset dir"),
                    None,
                ),
            );
        }
        _ => (),
    }
    let input_asset_path_stripped: Option<AssetPath<'static>> = match lookup {
        Lookup::Default => None,
        Lookup::One { ref path } => {
            if let Ok(p) = script_path.strip_prefix(path) {
                Some(AssetPath::from_path(p).clone_owned())
            } else {
                None
            }
        }
        Lookup::Two {
            ref default,
            ref script,
        } => {
            if let Ok(p) = script_path.strip_prefix(default) {
                Some(AssetPath::from_path(p).clone_owned())
            } else if let Ok(p) = script_path.strip_prefix(script) {
                // Okay, we need this separate asset source.
                let mut abs_path = invocation_dir.clone();
                abs_path.push(script);
                info_logs.push(format!(
                    "The 'script_dir://' assets directory: {:?}",
                    abs_path.display()
                ));
                app.register_asset_source(
                    "script_dir",
                    AssetSourceBuilder::platform_default(
                        abs_path.to_str().expect("script dir"),
                        None,
                    ),
                );
                Some(
                    AssetPath::from_path(p)
                        .with_source(AssetSourceId::from("script_dir"))
                        .clone_owned(),
                )
            } else {
                None
            }
        }
    };

    let input_asset_path: AssetPath<'static> = match input_asset_path_stripped {
        Some(p) => p,
        None => {
            if let Some(s) = script_path.to_str() {
                match AssetPath::try_parse(s) {
                    Ok(p) => p.clone_owned(),
                    Err(e) => {
                        eprintln!("Cannot convert {:?} to input path: {e}", &s);
                        return Ok(ExitCode::from(9));
                    }
                }
            } else {
                eprintln!(
                    "Cannot convert input path to UTF-8 string {:?}.",
                    script_path.display()
                );
                return Ok(ExitCode::from(10));
            }
        }
    };

    app.add_plugins(Nano9Plugins);
    // We emit info logs now because the `LogPlugin` is now registered and they
    // will be seen. Before adding `Nano9Plugins` no `info!` lines will be
    // shown.
    for log in info_logs {
        info!("{}", &log);
    }

    let extension = script_path
        .extension()
        .and_then(|ext| ext.to_str())
        .unwrap_or_default();
    match extension {
        "p8" | "png" => {
            app.add_systems(
                Startup,
                move |asset_server: Res<AssetServer>, mut commands: Commands| {
                    let shared_data = shared_data.unwrap_or_default();
                    let pico8_asset: Handle<Pico8Asset> = asset_server.load_with_settings(
                        &input_asset_path,
                        move |settings: &mut CartLoaderSettings| {
                            settings.shared_data = shared_data;
                        },
                    );
                    commands.insert_resource(Pico8Handle::from(pico8_asset));
                },
            );
        }
        "toml" | "lua" | "p8lua" => {
            if cfg!(not(feature = "pico8-to-lua")) && extension == "p8lua" {
                eprintln!(
                    "error: Must compile with 'pico8-to-lua' feature to handle 'p8lua' files."
                );
                return Ok(ExitCode::from(3));
            }
            app.add_systems(Startup, load_and_insert_pico8(input_asset_path));
        }
        ext => {
            eprintln!(
                "error: File has {ext:?} extension but only accepts extensions: .p8, .png, .lua, .p8lua, and .toml."
            );
            return Ok(ExitCode::from(1));
        }
    }

    if pause {
        app.add_systems(PreUpdate, pause_pico8_when_loaded);
    } else {
        app.add_systems(PreUpdate, run_pico8_when_loaded);
    }

    if app.is_plugin_added::<WindowPlugin>() {
        app.add_systems(
            Update,
            action::toggle_fullscreen.run_if(condition::on_just_pressed_with(
                KeyCode::Enter,
                vec![KeyCode::AltLeft, KeyCode::AltRight],
            )),
        );
    }
    #[cfg(feature = "minibuffer")]
    app.add_plugins(nano9::minibuffer::quick_plugin);
    #[cfg(feature = "debugdump")]
    bevy_mod_debugdump::print_schedule_graph(&mut app, Update);

    #[cfg(all(feature = "level", feature = "user_properties"))]
    app.add_systems(Startup, |reg: Res<AppTypeRegistry>| {
        bevy_ecs_tiled::map::export_types(&reg, "all-export-types.json", |name| true);
        bevy_ecs_tiled::map::export_types(&reg, "export-types.json", |name| {
            name.contains("bevy_ecs_tilemap::tiles") || name.contains("nano9")
        });
    });
    let app_exit = if !check {
        app.run()
    } else {
        use bevy::app::PluginsState;

        while app.plugins_state() == PluginsState::Adding {
            #[cfg(not(all(target_arch = "wasm32", feature = "web")))]
            bevy::tasks::tick_global_task_pools_on_main_thread();
        }

        app.finish();
        app.cleanup();

        app.update();
        app.should_exit().unwrap_or(AppExit::Success)
    };

    Ok(match app_exit {
        AppExit::Success => ExitCode::from(0),
        AppExit::Error(code) => ExitCode::from(code.get()),
    })
}