spritebox 0.6.0

Create 2D pixel art and game assets from text: sprites, backgrounds with parallax, tilemaps, procedural textures, UI and pixel fonts. A zero-dependency Rust library and CLI with PNG, atlas and TTF export.
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
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
//! The command-line tool: exit statuses, diagnostics and written files.

use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};

fn spritebox(args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_spritebox"))
        .args(args)
        .output()
        .expect("the binary runs")
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

/// A fresh directory for one test.
fn temp_dir(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("spritebox-cli-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

fn write(dir: &Path, name: &str, text: &str) -> String {
    let path = dir.join(name);
    std::fs::write(&path, text).unwrap();
    path.display().to_string()
}

const COIN: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/coin.spritebox");
const BAD: &str = "palette p\n  k #000\nsprite s 2x1 palette=p\n  kx\n";

#[test]
fn background_selection_camera_modes_and_no_partial_writes() {
    let dir = temp_dir("backgrounds");
    let input = write(
        &dir,
        "scene.spritebox",
        include_str!("fixtures/backgrounds/scene.spritebox"),
    );
    for mode in ["both", "flat", "layers", "none"] {
        let out = dir.join(mode);
        let rendered = spritebox(&[
            "render",
            &input,
            "--out",
            out.to_str().unwrap(),
            "--background",
            "scene",
            "--camera",
            "-3,1",
            "--background-mode",
            mode,
            "--theme",
            "all",
        ]);
        assert_eq!(rendered.status.code(), Some(0), "{}", stderr(&rendered));
        assert_eq!(
            out.join("background-0000.png").exists(),
            matches!(mode, "both" | "flat")
        );
        assert_eq!(
            out.join("background-0000-layer-0000.png").exists(),
            matches!(mode, "both" | "layers")
        );
        assert!(out.join("atlas.png").exists());
        assert!(out.join("preview.png").exists());
        let json = std::fs::read_to_string(out.join("spritebox.json")).unwrap();
        if mode != "none" {
            assert!(json.contains("\"camera\": [-3, 1]") || mode == "layers");
        }
    }
    let bad = dir.join("not-created");
    for arguments in [
        vec!["--background", "missing"],
        vec!["--background", "scene", "--background", "scene"],
        vec!["--camera", "x,0"],
        vec!["--background-mode", "bad"],
    ] {
        let mut args = vec!["render", &input, "--out", bad.to_str().unwrap()];
        args.extend(arguments);
        let failed = spritebox(&args);
        assert!(!failed.status.success());
        assert!(!bad.exists());
    }
    assert_eq!(
        spritebox(&["check", &input, "--camera", "0,0"])
            .status
            .code(),
        Some(2)
    );
    assert_eq!(
        spritebox(&["lint", &input, "--background-mode", "both"])
            .status
            .code(),
        Some(2)
    );
}

#[test]
fn check_valid_file() {
    let out = spritebox(&["check", COIN]);
    assert_eq!(out.status.code(), Some(0));
    assert!(stdout(&out).ends_with(": ok\n"), "{}", stdout(&out));
    let out = spritebox(&["check", COIN, "--json"]);
    assert_eq!(out.status.code(), Some(0));
    let json = stdout(&out);
    assert!(json.starts_with("{\"version\":1,\"file\":"), "{json}");
    assert!(
        json.contains("\"ok\":true,\"diagnostics\":[],\"written\":[]}"),
        "{json}"
    );
}

#[test]
fn check_invalid_file() {
    let dir = temp_dir("invalid");
    let file = write(&dir, "bad.spritebox", BAD);
    let out = spritebox(&["check", &file]);
    assert_eq!(out.status.code(), Some(1));
    let text = stderr(&out);
    assert!(
        text.contains(&format!(
            "{file}:2:5: error[invalid_argument]: Color `#000`"
        )),
        "{text}"
    );
    assert!(
        text.contains(&format!("{file}:4:4: error[unknown_name]: Key `x`")),
        "{text}"
    );
    assert!(text.ends_with(": 2 errors\n"), "{text}");

    let out = spritebox(&["check", "--json", &file]);
    assert_eq!(out.status.code(), Some(1));
    let json = stdout(&out);
    assert!(json.contains("\"ok\":false"), "{json}");
    assert!(json.contains(
        "{\"code\":\"invalid_argument\",\"severity\":\"error\",\"line\":2,\"column\":5,\"message\":\"Color `#000` must be `#rrggbb`, `#rrggbbaa` or `transparent`\"}"
    ), "{json}");
    assert!(
        json.contains("{\"code\":\"unknown_name\",\"severity\":\"error\",\"line\":4,\"column\":4,"),
        "{json}"
    );
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn check_reads_standard_input_and_rejects_bad_utf8() {
    let mut child = Command::new(env!("CARGO_BIN_EXE_spritebox"))
        .args(["check", "-", "--json"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"palette p\n  k #000000\n  \xff #000000\n")
        .unwrap();
    let out = child.wait_with_output().unwrap();
    assert_eq!(out.status.code(), Some(1));
    let json = stdout(&out);
    assert!(json.contains("\"file\":\"<stdin>\""), "{json}");
    assert!(json.contains("{\"code\":\"syntax\",\"severity\":\"error\",\"line\":3,\"column\":3,\"message\":\"The text is not valid UTF-8\"}"), "{json}");
}

#[test]
fn render_writes_files() {
    let dir = temp_dir("render");
    let out = spritebox(&[
        "render",
        COIN,
        "--out",
        dir.to_str().unwrap(),
        "--scale",
        "2",
        "--padding",
        "2",
        "--no-extrude",
        "--json",
    ]);
    assert_eq!(out.status.code(), Some(0), "{}", stderr(&out));
    let json = stdout(&out);
    for name in ["atlas.png", "spritebox.json", "preview.png"] {
        assert!(
            json.contains(&format!("{:?}", dir.join(name).display().to_string())),
            "{json}"
        );
    }
    let doc = spritebox::Document::parse(&std::fs::read_to_string(COIN).unwrap()).unwrap();
    let options = spritebox::ExportOptions {
        backgrounds: Default::default(),
        atlas: spritebox::AtlasOptions {
            padding: 2,
            extrude: false,
            ..Default::default()
        },
    };
    let export = doc.export(&options).unwrap();
    assert_eq!(
        spritebox::png::read_file(dir.join("atlas.png")).unwrap(),
        export.atlas.image
    );
    assert_eq!(
        std::fs::read_to_string(dir.join("spritebox.json")).unwrap(),
        export.to_json()
    );
    let preview = doc
        .preview(&spritebox::PreviewOptions {
            scale: 2,
            ..Default::default()
        })
        .unwrap();
    assert_eq!(
        spritebox::png::read_file(dir.join("preview.png")).unwrap(),
        preview
    );
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn render_writes_tilesets() {
    let dir = temp_dir("render-tiles");
    let tiles = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/tiles.spritebox");
    let out = spritebox(&["render", tiles, "--out", dir.to_str().unwrap()]);
    assert_eq!(out.status.code(), Some(0), "{}", stderr(&out));
    let doc = spritebox::Document::parse(&std::fs::read_to_string(tiles).unwrap()).unwrap();
    let export = doc.export(&spritebox::ExportOptions::default()).unwrap();
    assert_eq!(
        spritebox::png::read_file(dir.join("tileset-ground.png")).unwrap(),
        export.tilesets[0].image
    );
    let text = stdout(&out);
    let written: Vec<&str> = text
        .lines()
        .map(|l| l.rsplit(['/', '\\']).next().unwrap())
        .collect();
    assert_eq!(
        written,
        [
            "atlas.png",
            "tileset-ground.png",
            "spritebox.json",
            "preview.png"
        ]
    );
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn font_writes_truetype() {
    let dir = temp_dir("font");
    let font = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/font.spritebox");
    let path = dir.join("nested/hud.ttf");
    let out = spritebox(&[
        "font",
        font,
        "--out",
        path.to_str().unwrap(),
        "--family",
        "HUD Pixel",
        "--json",
    ]);
    assert_eq!(out.status.code(), Some(0), "{}", stderr(&out));
    let doc = spritebox::Document::parse(&std::fs::read_to_string(font).unwrap()).unwrap();
    let expected = doc
        .font("hud")
        .unwrap()
        .to_ttf(&spritebox::TtfOptions {
            family: Some("HUD Pixel".into()),
            ..Default::default()
        })
        .unwrap();
    assert_eq!(std::fs::read(&path).unwrap(), expected);
    assert!(stdout(&out).contains("hud.ttf"));

    // Several fonts need --font; an unknown font is bad usage too.
    let two = write(&dir, "two.spritebox", "font a height=1\nfont b height=1\n");
    let ttf = dir.join("x.ttf");
    let out = spritebox(&["font", &two, "--out", ttf.to_str().unwrap(), "--json"]);
    assert_eq!(out.status.code(), Some(2));
    assert!(
        stdout(&out).contains("choose one with --font"),
        "{}",
        stdout(&out)
    );
    let out = spritebox(&["font", &two, "--out", ttf.to_str().unwrap(), "--font", "c"]);
    assert_eq!(out.status.code(), Some(2));
    let out = spritebox(&["font", &two, "--out", ttf.to_str().unwrap(), "--font", "b"]);
    assert_eq!(out.status.code(), Some(0));
    assert!(ttf.exists());
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn imports_are_read_from_disk_relative_to_the_file() {
    let dir = temp_dir("imports");
    std::fs::create_dir_all(dir.join("art/shared")).unwrap();
    write(
        &dir,
        "art/shared/palettes.spritebox",
        "palette p\n  k #000000\n  x #00\n",
    );
    let main = write(
        &dir,
        "art/main.spritebox",
        "import shared/palettes.spritebox\nsprite s 1x1\n  k\n",
    );
    let out = spritebox(&["check", &main]);
    assert_eq!(out.status.code(), Some(1));
    let expected = dir.join("art").join("shared").join("palettes.spritebox");
    let text = stderr(&out);
    assert!(
        text.contains(&format!(
            "{}:3:5: error[invalid_argument]",
            expected.display()
        )),
        "{text}"
    );
    let out = spritebox(&["check", &main, "--json"]);
    assert!(
        stdout(&out).contains(&format!("\"file\":{:?}", expected.display().to_string())),
        "{}",
        stdout(&out)
    );
    write(
        &dir,
        "art/shared/palettes.spritebox",
        "palette p\n  k #000000\n",
    );
    let out = spritebox(&["render", &main, "--out", dir.join("out").to_str().unwrap()]);
    assert_eq!(out.status.code(), Some(0), "{}", stderr(&out));
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn render_does_not_write_invalid_files() {
    let dir = temp_dir("render-invalid");
    let file = write(&dir, "bad.spritebox", BAD);
    let out_dir = dir.join("out");
    let out = spritebox(&["render", &file, "--out", out_dir.to_str().unwrap()]);
    assert_eq!(out.status.code(), Some(1));
    assert!(!out_dir.exists());
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn usage_and_io_errors() {
    for args in [
        &[][..],
        &["draw", COIN],
        &["check"],
        &["check", COIN, "--frobnicate"],
        &["check", COIN, COIN],
        &["render", COIN],
        &["render", COIN, "--out"],
        &["render", COIN, "--out", "x", "--scale", "0"],
        &["check", COIN, "--out", "x"],
        &["check", COIN, "--no-extrude"],
        &["render", COIN, "--out", "x", "--max-side", "0"],
        &["font", COIN],
        &["render", COIN, "--out", "x", "--font", "hud"],
        &["render", COIN, "--out", "x", "--padding", "65"],
        &["lint", COIN, "--allow", "nope"],
        &["lint", COIN, "--deny"],
        &["lint", COIN, "--out", "x"],
        &["check", COIN, "--strict"],
        &["check", COIN, "--lint"],
        &["lint", COIN, "--lint"],
        &["render", COIN, "--out", "x", "--allow", "unused_key"],
    ] {
        let out = spritebox(args);
        assert_eq!(out.status.code(), Some(2), "{args:?}");
        assert!(stderr(&out).contains("Usage:"), "{args:?}");
    }
    let out = spritebox(&["check", "/no/such/file.spritebox", "--json"]);
    assert_eq!(out.status.code(), Some(3));
    assert!(stdout(&out).contains("\"code\":\"io\""), "{}", stdout(&out));

    let out = spritebox(&["--help"]);
    assert_eq!(out.status.code(), Some(0));
    assert!(stdout(&out).contains("spritebox check <file>"));
    let out = spritebox(&["--version"]);
    assert_eq!(
        stdout(&out),
        format!("spritebox {}\n", env!("CARGO_PKG_VERSION"))
    );
}

#[test]
fn lint_reports_warnings() {
    let dir = temp_dir("lint");
    let file = dir.join("noisy.spritebox");
    std::fs::write(
        &file,
        "palette p\n  g #3a7d44\n  h #468a50\n  k #000000\n\
         sprite leaf 3x3 palette=p\n  ggg\n  ghg\n  ggg\n",
    )
    .unwrap();
    let file = file.to_str().unwrap();

    // Warnings alone succeed.
    let out = spritebox(&["lint", file]);
    assert_eq!(out.status.code(), Some(0));
    let text = stderr(&out);
    assert!(
        text.contains(&format!(
            "{file}:4:3: warning[unused_key]: Nothing uses key `k` of palette `p`"
        )),
        "{text}"
    );
    assert!(
        text.contains(&format!("{file}:7:4: warning[orphan_pixel]: A lone pixel")),
        "{text}"
    );
    assert!(text.ends_with(": 2 warnings\n"), "{text}");

    // --strict fails on any warning, --deny on its codes; --allow drops a code.
    assert_eq!(
        spritebox(&["lint", file, "--strict"]).status.code(),
        Some(1)
    );
    assert_eq!(
        spritebox(&["lint", file, "--deny", "orphan_pixel"])
            .status
            .code(),
        Some(1)
    );
    let out = spritebox(&[
        "lint",
        file,
        "--allow",
        "orphan_pixel",
        "--deny",
        "orphan_pixel",
    ]);
    assert_eq!(out.status.code(), Some(0));
    assert!(stderr(&out).ends_with(": 1 warning\n"), "{}", stderr(&out));

    let out = spritebox(&["lint", file, "--json", "--strict"]);
    assert_eq!(out.status.code(), Some(1));
    let json = stdout(&out);
    assert!(json.contains("\"ok\":false"), "{json}");
    assert!(
        json.contains("{\"code\":\"unused_key\",\"severity\":\"warning\",\"line\":4,\"column\":3,"),
        "{json}"
    );

    // A clean file, and a file with errors, which are not linted.
    let out = spritebox(&["lint", COIN, "--strict"]);
    assert_eq!(out.status.code(), Some(0));
    assert!(stdout(&out).ends_with(": ok\n"), "{}", stdout(&out));
    let bad = dir.join("bad.spritebox");
    std::fs::write(&bad, "palette p\n  g #3a7d4\n").unwrap();
    let out = spritebox(&["lint", bad.to_str().unwrap()]);
    assert_eq!(out.status.code(), Some(1));
    assert!(
        stderr(&out).contains("error[invalid_argument]"),
        "{}",
        stderr(&out)
    );
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn lint_fails_on_warnings_past_the_limit() {
    // 1250 unused keys, then noise that comes after the first 1000 warnings.
    let dir = temp_dir("lint-limit");
    let mut text = String::new();
    let mut key = 0x100u32;
    for p in 0..5 {
        text.push_str(&format!("palette p{p}\n"));
        for _ in 0..250 {
            let k = char::from_u32(key).unwrap();
            text.push_str(&format!("  {k} #000000\n"));
            key += 1;
        }
    }
    text.push_str(
        "palette q\n  g #3a7d44\n  h #468a50\nsprite leaf 3x3 palette=q\n  ggg\n  ghg\n  ggg\n",
    );
    let file = dir.join("many.spritebox");
    std::fs::write(&file, text).unwrap();
    let file = file.to_str().unwrap();

    let out = spritebox(&["lint", file, "--deny", "orphan_pixel"]);
    assert_eq!(out.status.code(), Some(1));
    let text = stderr(&out);
    assert!(
        !text.contains("orphan_pixel"),
        "the noise is past the limit"
    );
    assert!(
        text.ends_with(": 1251 warnings, of which the first 1000 are shown\n"),
        "{}",
        text.lines().last().unwrap_or_default()
    );
    let out = spritebox(&["lint", file, "--json"]);
    assert_eq!(out.status.code(), Some(0));
    assert!(stdout(&out).contains("],\"omitted\":251,\"written\":[]}"));
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn render_marks_lint_on_the_preview() {
    let dir = temp_dir("render-lint");
    let example = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/lint.spritebox");
    let (plain, marked) = (dir.join("plain"), dir.join("marked"));
    let out = spritebox(&["render", example, "--out", plain.to_str().unwrap()]);
    assert_eq!(out.status.code(), Some(0), "{}", stderr(&out));
    let out = spritebox(&[
        "render",
        example,
        "--out",
        marked.to_str().unwrap(),
        "--lint",
    ]);
    assert_eq!(out.status.code(), Some(0), "{}", stderr(&out));
    let plain = spritebox::png::read_file(plain.join("preview.png")).unwrap();
    let marked = spritebox::png::read_file(marked.join("preview.png")).unwrap();
    assert!(marked.height() > plain.height());
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn ui_themes_and_screen_rendering() {
    let dir = temp_dir("ui");
    let file = write(
        &dir,
        "ui.spritebox",
        "palette p\n  w #ffffff\nsprite dot 1x1\n  w\ntheme dark of p\n  w #000000\nscreen view 1x1\n  dot at 0,0\n",
    );
    let directory = dir.join("all");
    let output = spritebox(&[
        "render",
        &file,
        "--out",
        directory.to_str().unwrap(),
        "--theme",
        "all",
        "--preview",
    ]);
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert!(directory.join("atlas-dark.png").is_file());
    assert!(
        std::fs::read_to_string(directory.join("spritebox.json"))
            .unwrap()
            .contains("atlas-dark.png")
    );
    let target = dir.join("view.png");
    let output = spritebox(&[
        "render",
        &file,
        "--screen",
        "view",
        "--theme",
        "dark",
        "--scale",
        "3",
        "--out",
        target.to_str().unwrap(),
    ]);
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let image = spritebox::png::read_file(&target).unwrap();
    assert_eq!((image.width(), image.height()), (3, 3));
    assert_eq!(image.pixel(0, 0), Some(spritebox::Color::BLACK));
    let output = spritebox(&[
        "render",
        &file,
        "--screen",
        "view",
        "--out",
        target.to_str().unwrap(),
    ]);
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert_eq!(spritebox::png::read_file(&target).unwrap().width(), 1);
    let missing = dir.join("missing.png");
    let output = spritebox(&[
        "render",
        &file,
        "--screen",
        "absent",
        "--out",
        missing.to_str().unwrap(),
    ]);
    assert_eq!(output.status.code(), Some(1));
    assert!(!missing.exists());
    let output = spritebox(&[
        "render",
        &file,
        "--theme",
        "absent",
        "--out",
        missing.to_str().unwrap(),
    ]);
    assert_eq!(output.status.code(), Some(1));
    assert!(!missing.exists());
    let output = spritebox(&[
        "render",
        &file,
        "--screen",
        "view",
        "--theme",
        "all",
        "--out",
        missing.to_str().unwrap(),
    ]);
    assert_eq!(output.status.code(), Some(2));
    std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn background_scale_writes_enlarged_copies_and_keeps_native_files() {
    let dir = temp_dir("background-scale");
    let input = write(
        &dir,
        "scene.spritebox",
        include_str!("fixtures/backgrounds/scene.spritebox"),
    );
    let render = |name: &str, extra: &[&str]| {
        let out = dir.join(name);
        let mut args = vec!["render", &input, "--out", out.to_str().unwrap()];
        args.extend(["--theme", "all", "--camera", "2,0"]);
        args.extend(extra);
        let rendered = spritebox(&args);
        assert_eq!(rendered.status.code(), Some(0), "{}", stderr(&rendered));
        out
    };
    let native = render("native", &[]);
    let scaled = render("scaled", &["--background-scale", "3"]);
    let natives: Vec<String> = std::fs::read_dir(&native)
        .unwrap()
        .map(|e| e.unwrap().file_name().into_string().unwrap())
        .collect();
    let mut enlarged = 0;
    for name in &natives {
        // Native files, and the metadata, are byte-identical with and without the flag.
        assert_eq!(
            std::fs::read(native.join(name)).unwrap(),
            std::fs::read(scaled.join(name)).unwrap(),
            "{name}"
        );
        let Some(stem) = name
            .strip_suffix(".png")
            .filter(|s| s.starts_with("background-"))
        else {
            continue;
        };
        let small = spritebox::png::decode(&std::fs::read(native.join(name)).unwrap()).unwrap();
        let big_name = format!("{stem}@3x.png");
        let big = spritebox::png::decode(&std::fs::read(scaled.join(&big_name)).unwrap())
            .unwrap_or_else(|e| panic!("{big_name}: {e}"));
        assert_eq!(
            (big.width(), big.height()),
            (small.width() * 3, small.height() * 3)
        );
        // Every enlarged block equals its native pixel.
        for y in 0..big.height() {
            for x in 0..big.width() {
                assert_eq!(
                    big.pixel(x, y),
                    small.pixel(x / 3, y / 3),
                    "{big_name} {x},{y}"
                );
            }
        }
        enlarged += 1;
    }
    // A flat image and two layers, for the base colors and one theme.
    assert_eq!(enlarged, 6, "{natives:?}");
    let count = std::fs::read_dir(&scaled).unwrap().count();
    assert_eq!(count, natives.len() + enlarged);
    let json = std::fs::read_to_string(scaled.join("spritebox.json")).unwrap();
    assert!(!json.contains("@3x"), "{json}");

    let bad = dir.join("not-created");
    for arguments in [
        vec!["--background-scale", "1"],
        vec!["--background-scale", "9"],
        vec!["--background-scale", "x"],
        vec!["--background-scale", "2", "--background-scale", "2"],
    ] {
        let mut args = vec!["render", &input, "--out", bad.to_str().unwrap()];
        args.extend(arguments.iter().copied());
        let failed = spritebox(&args);
        assert_eq!(failed.status.code(), Some(2), "{arguments:?}");
        assert!(!bad.exists());
    }
    let screen_out = dir.join("hud.png");
    let screen = spritebox(&[
        "render",
        &input,
        "--screen",
        "hud",
        "--out",
        screen_out.to_str().unwrap(),
        "--background-scale",
        "2",
    ]);
    assert_eq!(screen.status.code(), Some(2));
    // Image limits are checked before anything is written.
    let huge = write(
        &dir,
        "huge.spritebox",
        "palette p\n  a #000000\nsurface s 4000x8\n  rect r at=0,0 size=4000x8 key=a\n\
         background b 4000x8\n  layer l 4000x8\n    place surface s at=0,0\n",
    );
    let huge_out = dir.join("huge");
    let failed = spritebox(&[
        "render",
        &huge,
        "--out",
        huge_out.to_str().unwrap(),
        "--background-scale",
        "3",
    ]);
    assert_eq!(failed.status.code(), Some(1), "{}", stderr(&failed));
    assert!(
        stderr(&failed).contains("enlarged 3 times"),
        "{}",
        stderr(&failed)
    );
    assert!(!huge_out.exists());
}